user8042669
user8042669

Reputation:

Python: What is Wrong With This datetime.strptime Parsing?

I try to parse a string into a datetime object:

from datetime import datetime
last_time = '2018-06-01T19:00:00.000000000Z'
datetime.strptime(last_time, '%Y-%m-%dT%H:%M:%S.%fZ')

unfortunately, this fails:

ValueError: time data '2018-06-04T08:44:10.000000000Z' \
does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

What am I doing wrong?

This describes the parameters for parsing:

https://docs.python.org/2/library/datetime.html#strftime-strptime-behavior

Upvotes: 4

Views: 258

Answers (1)

jezrael
jezrael

Reputation: 862501

Parameter %f need microseconds precision, check docs:

When used with the strptime() method, the %f directive accepts from one to six digits and zero pads on the right. %f is an extension to the set of format characters in the C standard (but implemented separately in datetime objects, and therefore always available).

So add last zeros with Z:

from datetime import datetime
last_time = '2018-06-01T19:00:00.000000000Z'
a = datetime.strptime(last_time, '%Y-%m-%dT%H:%M:%S.%f000Z')

Or remove last 4 values:

from datetime import datetime
last_time = '2018-06-01T19:00:00.000000000Z'
a = datetime.strptime(last_time[:-4], '%Y-%m-%dT%H:%M:%S.%f')
print (a)
2018-06-01 19:00:00

Upvotes: 4

Related Questions