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 change timezone of datetime object using timezone abbreviation

I bet this is easy, but darned if I can figure it out. Standard disclaimer that
honestly, I’ve tried to figure this out.

How do you change the time zone of a datetime.datetime object by using the
abbreviation of the time zone? For example, if I have an object that has a timezone
of EST, how do I get that same datetime for PST?

How would you do something like 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

from datetime import datetime
now = datetime.now().astimezone()
pst = your_magic_function(now, 'PST)

>Solution :

Specify the time zone in .astimezone() using the ZoneInfo class. The default is your local time zone. The available ZoneInfo keys are listed in zoneinfo.available_timezones(). "PST" is not one of them since the Pacific zone varies between PST and PDT depending on the date.

# "pip install tzdata" for latest time zone data on Windows.
import datetime as dt
import zoneinfo as zi

# Being specific to get Eastern since I'm in PST now.
now = dt.datetime.now().astimezone(zi.ZoneInfo('US/Eastern'))
print(now)
print(now.astimezone(zi.ZoneInfo('US/Pacific')))

Output:

2024-11-04 20:38:51.401658-05:00
2024-11-04 17:38:51.401658-08:00
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