pythondatetimetimedstpytz

Regarding the pytz module and the time module in Python


I am a beginner in Python and trying to understand how to work with dates and times. Could you help me understand the following concept?

In the time module, we can get the local timezone by doing the following:

import time

if time.daylight:
    local_timezone_name = time.tzname[0]
    utc_offset = time.timezone
else:
    local_timezone_name = time.tzname[1]
    utc_offset = time.altzone

So what I want to clarify is:

  1. Isn't it sufficient to use the time module as above when dealing with local time zones instead of using the pytz module? If not why pytz module is necessary?

  2. What advantages does one gain by using the pytz module when dealing with dates and times in Python? (I don't understand how it differs from what Python already has built into it and how it handles dates and times efficiently?)


Solution

  • A long story.

    Note: pytz is now obsolete (since two weeks), so with Python 3.9 you can uses directly standard libraries.

    The problem: pytz is updated independently from Python releases, so it could change quickly the timezone changes. It is not so seldom that within a week or so a country decide to change daylight time implementation. This would cause a lot of problem using standard Python, were you do not update so often (and it will requires a lot of burdens, just to update one line in timezone file). So Python didn't include timezone information, but for UTC (but it could handle time offsets and daylight flag), and some information about your local timezone (and ev. daylight).

    Now it seems they found a solution, but Python 3.9 is very new (it was released two weeks ago).

    So, if you do not have python 3.9, pytz is the way to go. You have updated timezones and daylight periods.