Search code examples
pythondatetimetimezonestandard-librarypytz

Is there any practical use for the datetime.timezone class in Python 3 standard library?


The documentation for the datetime.timezone class only says:

A class that implements the tzinfo abstract base class as a fixed offset from the UTC.

And it accepts a timedelta as its argument.

I never saw an example using it directly from other's code snippets, although I believe there must be some use of it, otherwise there is no point Python would expose this API. So in what situation would directly using this class be advised? What advantage would that be over using a dedicated library, such as pytz?


Solution

  • From the Python 3 documentation:

    The datetime module supplies a simple concrete subclass of tzinfo, timezone, which can represent timezones with fixed offset from UTC such as UTC itself or North American EST and EDT.

    The basic idea being that for timezones that are simply offsets of UTC time (i.e., UTC +/- some fixed number of minutes), implementing all the methods required for tzinfo objects is more effort than necessary, so you can simply subclass the timezone object with the offset value.

    The documentation itself also recommends pytz for working with timezones:

    pytz library brings the IANA timezone database (also known as the Olson database) to Python and its usage is recommended