-
-
Notifications
You must be signed in to change notification settings - Fork 33.2k
Description
Bug report
Bug description:
I often use datetime.astimezone()
to make my datetime objects tz-aware. Using astimezone(tz=None)
is very convenient, but the tzinfo object that is returned has a tzname()
that can't be passed to ZoneInfo:
import datetime
from zoneinfo import ZoneInfo
dt=datetime.datetime.now().astimezone()
dt.tzname()
'Eastern Standard Time'
If I try
ZoneInfo(dt.tzname())
I get
ZoneInfoNotFoundError: 'No time zone found with key Eastern Standard Time'
I understand why, and I almost submitted this issue for zoneinfo
, but after looking at the docs, I thought it would be more appropriate for the datetime
module.
What I've done recently is to create a dictionary to map the timezones to something ZoneInfo
has a key for:
US_timezone_dict = {'eastern standard time':'US/Eastern',
'eastern daylight time':'US/Eastern',
'central standard time':'US/Central',
'central daylight time':'US/Central',
'mountain standard time':'US/Mountain',
'mountain daylight time':'US/Mountain',
'us mountain standard time':'US/Arizona',
'pacific standard time':'US/Pacific',
'pacific daylight time':'US/Pacific',
'alaska standard time':'US/Alaska',
'aleutian standard time':'US/Aleutian',
'hawaiian standard time':'US/Hawaii',
}
_timezone = dt.tzname()
if _timezone and _timezone.lower() in US_timezone_dict:
_timezone = US_timezone_dict[_timezone.lower()]
Now this works for me, but it would be nice is dt.astimezone()
would return a tzinfo
with a name that ZoneInfo
knows about.
I can do
dt=datetime.datetime.now().astimezone(ZoneInfo('US/Eastern'))
dt.tzname()
Out[32]: 'EST'
but I don't always know which time zone I will be in when I run my code.
Thanks.
CPython versions tested on:
3.11
Operating systems tested on:
Windows