Reputation: 1175
I am running the below code
import datetime
d =datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z', '%Y-%m-%d %H:%M:%S.%f')
I am getting an exception as
ValueError("time data '2018-11-20T09:12:01.7511709Z' does not match format '%Y-%m-%d %H:%M:%S.%f'",))
What is wrong with my code here. please help.
Upvotes: 1
Views: 811
Reputation: 16624
%f
directive accepts from one to six digits, try omit last two digits of your input:
datetime.datetime.strptime('2018-11-20T09:12:01.7511709Z'[:-2], '%Y-%m-%dT%H:%M:%S.%f')
Upvotes: 3
Reputation: 1116
Looks like you need to truncate your microseconds to 6 decimal places (documentation seems to support this: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior)
The following worked fine:
import datetime
d = datetime.datetime.strptime('2018-11-20T09:12:01.751171Z', '%Y-%m-%dT%H:%M:%S.%fZ')
If you want to correctly round your microseconds, try this:
import datetime
time_string = '2018-11-20T09:12:01.7511709Z'
date_time, microseconds = time_string.split('.')
microseconds = microseconds[:-1]
rounding = len(microseconds) - 6
divisor = 10 ** rounding
new_micros = int(round(int(microseconds) / divisor, 0))
time_string = date_time + '.' + str(new_micros) + 'Z'
d = datetime.datetime.strptime(time_string, '%Y-%m-%dT%H:%M:%S.%fZ')
Upvotes: 2
Reputation: 87
Also the easiest way:
from datetime import datetime
str(datetime.now())
'2018-11-20 14:58:05.329281'
Upvotes: 0