So i have this kind f format:
'%Y-%m-%d %H:%M:%S.%f'
date_time = datetime.now()
Ouput
'2019-04-15 07:52:14.211697'
And i want to change is into this format: '%Y-%m-%d %H:%M:%S,%f'
This is what i have try:
time = datetime.strptime(str(date_time), '%Y-%m-%d %H:%M:%S,%f')
And this is the error
:
ValueError: time data '2019-04-15 07:52:14.211697' does not match format '%Y-%m-%d %H:%M:%S,%f'
Edit
So i have this string
:
maches = regex.findall(
'[0-9]{4}-(?:0[1-9]|1[0-2])-(?:0[1-9]|[1-2][0-9]|3[0-1]) (?:2[0-3]|[01][0-9]):[0-5][0-9]:[0-5][0-9],[0-9][0-9][0-9]',
line)
match[0] = '2019-03-13 17:35:35,855'
And i want to convert it to Datetime
:
time = datetime.strptime(maches[0], '%Y-%m-%d %H:%M:%S,%f')
And this returned another format
:
2019-03-13 17:35:35.855000
Why ?
You want to use strftime:
str_time = datetime.strftime(date_time, '%Y-%m-%d %H:%M:%S,%f')
A quick comparison of strftime and strptime :
strftime() is used to convert a datetime object to a string
strptime() is used to convert a date string to a datetime object
Also here's a good resource in the documentation describing the differences: strftime() and strptime() Behavior
Response to Question Edit
In response to your edit strptime takes a string date and converts it into a datetime object. The format you pass to it just tells it how to parse the string to datetime. It does not dictate it's print format. You are calling print on a datetime object in this case so the output is dictated by the __str__
method on the datetime object.
If you want to print it in a certain way pass it to strftime with the format you want to output it as:
obj_time = datetime.strptime(maches[0], '%Y-%m-%d %H:%M:%S,%f')
print(datetime.strftime(obj_time , '%Y-%m-%d %H:%M:%S,%f'))
Use strftime.
date_time = datetime.now()
print(date_time)
print(datetime.strftime(date_time, '%Y-%m-%d %H:%M:%S,%f'))
2019-04-15 10:26:08.637630
2019-04-15 10:26:08,637630
使用此格式,您将获得以下格式:'%Y-%m-%d%H:%M:%S,%f'
print '{:%Y-%m-%d %H:%M:%S.%f}'.format(date_time)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.