yun's attic

Time Zone in Python - Tip of the Iceberg

Time zone is such a messy subject, and I don’t even know what to start with.

At my previous job I had this photo saved from a stackoverflow answer:

time zone conversion

so that every time I need to do some time zone conversion magic, I have a quick reference to go to. Because seriously, how do you expect anyone to memorize all that?

Today I’m playing with some time zone stuff again for the API with my autotrader database, and encountered a new problem/feature that somehow entirely evaded my attention in the past. In a nutshell, these two code blocks produced different results, and I couldn’t understand why:

  1. use tzinfo=... when creating a datetime.datetime object

    import datetime as dt
    from pytz import timezone
    
    tz = timezone('Europe/Amsterdam')
    dt.datetime(2020, 2, 1, 10, tzinfo=tz)
    

    which produces this result:

    datetime.datetime(2020, 2, 1, 10, 0, tzinfo=<DstTzInfo 'Europe/Amsterdam' LMT+0:20:00 STD>)
    
  2. use timezone.localize() on an existing datetime.datetime object

    tz = timezone('Europe/Amsterdam')
    tz.localize(dt.datetime(2020, 2, 1, 10))
    

    which gives this:

    datetime.datetime(2020, 2, 1, 10, 0, tzinfo=<DstTzInfo 'Europe/Amsterdam' CET+1:00:00 STD>)
    

Why are they not the same???

Answer is, method #1 returns a time offset which is the Local Mean Time (LMT), which is purely decided by the longitude of the location in question. On the other hand, method #2 gives the actual time zone, which is more of a social structure than a geological one, and that is what I wanted.

Here CET stands for Central European Time, which is the time zone observed in the Netherlands.

I didn’t feel like using any third-party packages like Arrow or Pendulum. They each have their own nice features, but integrating them with other libraries (like SQLAlchemy I’m using) sometimes is a bit messy (and more work to do).

Maybe at some point I’ll end up writing a series about how I approach time zones. Part of me still hopes that we’ll all switch to UTC some time soon. Or at least, get rid of daylight saving.

Menu