Nisar
Nisar

Reputation: 888

Unable to parse the strptime in python

I am converting the datetime into time. My JSON datetime format is "2017-01-02T19:00:07.9181202Z". I have placed my code below:

from datetime import datetime
date_format = datetime.strptime('2017-01-02T19:00:07.9181202Z', '%Y-%m-%dT%H:%M:%S.%fZ')
time = date_format.strftime("%I:%M %p")
print(time)

Error message as below:

enter image description here

After that I read this python date-time document. It says that microsecond digit should be 6. But, JSON date-time microsecond has 7 digit.

Message from Python document:

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

I need result like 07:00 PM format. Is there any alternative method?

Thanks in advance.

Upvotes: 0

Views: 178

Answers (1)

jbasko
jbasko

Reputation: 7330

If you're sure that the input will always be like that, you can just remove the extra digit before passing that string to strptime:

date_format = datetime.strptime('2017-01-02T19:00:07.9181202Z'[:-2] + 'Z', '%Y-%m-%dT%H:%M:%S.%fZ')

This is dirty, but gives the idea - remove the last two characters (the extra digit and "Z"), re-add the "Z".

Upvotes: 1

Related Questions