Reputation: 103
Is it possible to get the inverse of this operation:
import dateutil.tz
tz_ny = dateutil.tz.tz.gettz('America/New_York')
print(type(tz_ny))
print(tz_ny)
This prints:
dateutil.tz.tz.tzfile
tzfile('/usr/share/zoneinfo/America/New_York')
How to recover 'America/New_York' given tz_ny of type tzfile?
N.B. tz_ny.tzname(datetime.datetime(2017,1,1))
return 'EST' or 'EDT' if the date is in the summer.
Upvotes: 4
Views: 2358
Reputation: 5301
If you want just the timezone name from a tzfile
and not the full path, you can e.g. do
import dateutil.tz
tz_ny = dateutil.tz.tz.gettz('America/New_York')
tz_ny_zone= "/".join(tz_ny._filename.split('/')[-2:])
print(tz_ny_zone)
which gets you
'America/New_York'
EDIT: Just for the sake of completeness, since the title only mentions tzfile
: Besides dateutil
there are other modules which can be used to get a tzfile
. One way is using timezone()
from the pytz
module:
import pytz
tz_ny_pytz = pytz.timezone('America/New_York')
Depending on which module you used in the first place, the class of tzfile
differs
print(type(tz_ny))
print(type(ty_ny_pytz))
prints
<class 'dateutil.tz.tz.tzfile'>
<class 'pytz.tzfile.America/New_York'>
For the pytz
object, there is a more direct way of accessing the timezone in human readable form, using the .zone
attribute:
print(tz_ny_pytz.zone)
produces
'America/New_York'
Upvotes: 2
Reputation: 103
Turns out that there is a protected member variable....
tz_ny._filename
is
'/usr/share/zoneinfo/America/New_York'
Upvotes: 2