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

How to specify the timezone in a python timestamp literal?

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:

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

 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.

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