Swizec Teller - a geek with a hatswizec.com

Senior Mindset Book

Get promoted, earn a bigger salary, work for top companies

Senior Engineer Mindset cover
Learn more

    Handling timezones in python

    Time Selector

    A couple of days ago I started refactoring some code to handle timezones better. The problem manifests as a single time appearing at different times in different parts of the application.

    Granted, a lot of it is more of a UX problem along the lines of my rant on why computers don't handle timezones intuitively. But there's a deeper issue with the fact that the codebase is handling timezones rather naively.

    Until a week ago I would have done it exactly the same way.

    Naive approach

    Usually when people first implement timing in an application they (or rather we) don't really care about timezones. You just take a timestamp and store it in a database. This suffices for most use cases ... sure the times are in whatever timezone your server is set to but as long as you're using the same server for everything and you're only using times for timestamps when objects were inserted into the database and for logging ...

    It's just not a problem.

    Then you are faced with a distributed environment and suddenly all those timestamps start acting funny, or maybe you have users in different timezones and you want to display times to them.

    Still an easy problem to solve; just handle all times as UTC internally and translate to the proper timezone when producing outputs. Easy as pie right?

    And then you notice strange things happen around daylight savings. Suddenly 3am happens twice on the 31st of October in Slovenia ... but the same thing only happens a week later in the US. And some states in the US don't even observe DST and now what do you do?


    Those ambiguous periods are the main thing pytz takes care of.

    To be perfectly honest I never even considered this problem before reading the documentation and having my mind blown. There's just so much intricacies over keeping up to date on what each timezone is doing and what particular timezone a user is in right now ... it's insane!

    Even though pytz claims they don't take care of ambiguous periods like Poland rewinding their clocks half an hour in 1915 to start using CET, they're still pretty vital for everything else.

    Of course you'll still want to handle all times internally as UTC otherwise doing time arithmetic can get quite hairy, although pytz can supposedly handle that too ... but at least now it should be possible to correctly get the UTC time out of user input and then correctly display the result.

    An example:

    from datetime import datetime
    from pytz import *
    eastern = timezone('US/Eastern')
    loc_dt = eastern.localize(datetime(2011, 11, 2, 7, 27, 0))
    print loc_dt
    # 2011-11-02 07:27:00-04:00
    ljubljana = timezone("Europe/Ljubljana")
    print loc_dt.astimezone(ljubljana)
    # 2011-11-02 12:27:00+01:00


    Turns out there's much more to timezones than one might think. Just goes to show why all those other coders are spending so much time on trivial stuff ... nothing is really trivial. Nothing.

    And let's not even get into leap seconds.

    Published on November 2nd, 2011 in Coordinated Universal Time, Daylight saving time, Lists of time zones, Telstar Logistics, timezone, Uncategorized, UTC

    Did you enjoy this article?

    Continue reading about Handling timezones in python

    Semantically similar articles hand-picked by GPT-4

    Senior Mindset Book

    Get promoted, earn a bigger salary, work for top companies

    Learn more

    Have a burning question that you think I can answer? Hit me up on twitter and I'll do my best.

    Who am I and who do I help? I'm Swizec Teller and I turn coders into engineers with "Raw and honest from the heart!" writing. No bullshit. Real insights into the career and skills of a modern software engineer.

    Want to become a true senior engineer? Take ownership, have autonomy, and be a force multiplier on your team. The Senior Engineer Mindset ebook can help πŸ‘‰ swizec.com/senior-mindset. These are the shifts in mindset that unlocked my career.

    Curious about Serverless and the modern backend? Check out Serverless Handbook, for frontend engineers πŸ‘‰ ServerlessHandbook.dev

    Want to Stop copy pasting D3 examples and create data visualizations of your own? Learn how to build scalable dataviz React components your whole team can understand with React for Data Visualization

    Want to get my best emails on JavaScript, React, Serverless, Fullstack Web, or Indie Hacking? Check out swizec.com/collections

    Did someone amazing share this letter with you? Wonderful! You can sign up for my weekly letters for software engineers on their path to greatness, here: swizec.com/blog

    Want to brush up on your modern JavaScript syntax? Check out my interactive cheatsheet: es6cheatsheet.com

    By the way, just in case no one has told you it yet today: I love and appreciate you for who you are ❀️

    Created by Swizec with ❀️