Skip to content Skip to sidebar Skip to footer

How To Find The Timezone Name From A Tzfile In Python

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.t

Solution 1:

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:

importpytztz_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'

Solution 2:

Turns out that there is a protected member variable....

tz_ny._filename

is

'/usr/share/zoneinfo/America/New_York'

Post a Comment for "How To Find The Timezone Name From A Tzfile In Python"