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:
from datetime import datetime
now = datetime.now().astimezone()
pst = your_magic_function(now, 'PST)
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