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?
>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())