The following works:
datetime.strptime("2023-11-15 01:02:03.123456", "%Y-%m-%d %H:%M:%S.%f"))
Out[11]: datetime.datetime(2023, 11, 15, 1, 2, 3, 123456)
But the following fails:
datetime.strptime("2023-11-15 01:02:03.123456", "%Y-%m-%d %H:%M:%S.%f%Z"))
ValueError: time data ‘2023-11-15 01:02:03.123456’
does not match format ‘%Y-%m-%d %H:%M:%S.%f%Z’
How should that timestamp literal be set up to specify UTC-8 ?
Update I also tried
"2023-11-15 01:02:03.123456 -08:00"
That did not work. I’m not sure what the syntax is here.
>Solution :
%Z can only parse timezone names (e.g., ‘UTC’, ‘EST’, ‘CST’) and not offsets like ‘UTC-8’, you need to use %z (see docs):
>>> from datetime import datetime
>>> datetime_str = "2023-11-15 01:02:03.123456-0800" # UTC-8
>>> datetime_object = datetime.strptime(datetime_str, "%Y-%m-%d %H:%M:%S.%f%z")
>>> datetime_object
datetime.datetime(2023, 11, 15, 1, 2, 3, 123456, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=57600)))
n.b. Make sure your timezone offset string conforms to the +HHMM or -HHMM format.