Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a way to fix this datetime error?

I’m getting this error:

ValueError: time data '2022-01-20T15:30:57.2648531Z' does not match format '%Y-%m-%dT%H:%M:%S.%fZ'

here is my code:

import datetime
 
date_string = '2022-01-20T15:30:57.2648531Z'
date_format = datetime.datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%fZ")
unix_time = datetime.datetime.timestamp(date_format)
print(unix_time)

I have tested removing the final number in the time data and it worked. It seems you can only have 6 numbers in the millisecond spot. Is there a way to bypass/fix this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

It seems you can only have 6 numbers in the millisecond spot

It’s actually microseconds, the %f specifier matches a 6-digit microsecond value. If you have a 7-digit number then the precision is more than one microsecond.

datetime objects do not support higher precision than microseconds, so you can just throw away the last digit. You can do this in multiple ways. Since according to your format specifier your string should always have the same length, you can simply trim it before converting.

import datetime 

date_string = '2022-01-20T15:30:57.2648531Z'
date_string = date_string[:26] # trim anything past the 6th decimal digit

d = datetime.datetime.strptime(date_string, "%Y-%m-%dT%H:%M:%S.%f")
print(d.timestamp())

Since your date is in ISO format, you can also use datetime.datetime.fromisoformat(), which should make your life easier:

import datetime 

date_string = '2022-01-20T15:30:57.2648531Z'
date_string = date_string[:26] # trim anything past the 6th decimal digit

d = datetime.datetime.fromisoformat(date_string)
print(d.timestamp())
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading