Search code examples
pythonpython-3.xtimezonepython-3.5pytz

How can I convince DateTime object (initialized with pytz timezone) to get me a timezone code recognized by pytz? (Python)


import pytz
import datetime

timezone = pytz.timezone('Poland')
date = timezone.localize(datetime.datetime(2018, 10, 1))
pytz.timezone(date.tzname())

Unfortunately in Python 3.5.2, with it crashes with

Traceback (most recent call last):
  File "timezones.py", line 6, in <module>
    pytz.timezone(date.tzname())
  File "/usr/local/lib/python3.5/dist-packages/pytz/__init__.py", line 178, in timezone
    raise UnknownTimeZoneError(zone)
pytz.exceptions.UnknownTimeZoneError: 'CEST'

In one part of program timezone aware time object is created. In other part it is necessary to get timezone identifier back.

To avoid XY issues: I am calculating sunrise and sunset data using skyfield library. To do this I need to pass timezone as one of parameters.

From what I see at https://docs.python.org/3/library/datetime.html there is a timezone but for setting timezone, not getting it.


Solution

  • The TZ database timezone name is stored as the zone attribute of the zone object returned by pytz.timezone():

    >>> import pytz
    >>> import datetime
    >>> 
    >>> timezone = pytz.timezone('Poland')
    >>> date = timezone.localize(datetime.datetime(2018, 10, 1))
    >>> date.tzinfo.zone
    'Poland'
    

    As you can see, the zone object itself is available as date.tzinfo after calling localize(), so you can just use that directly instead of passing the name back into pytz.timezone() if that's why you need it.