What you need to know about datetimes

Audience level:
Best Practices/Patterns
March 10th 10:25 a.m. – 11:05 a.m.


`time`, `datetime`, and `calendar` from the standard library are a bit messy. Find out what to use where and how (particularly when you have users in many timezones), and what extra modules you might want to look into.


  • Defining an "instant"
  • Silly timezones
    • In the words of Armin Ronacher:
      • Always measure and store time in UTC
      • Do not use offset aware datetimes
      • If you are taking in user input that is in local time, immediately convert it to UTC. If that conversion would be ambiguous let the user know.
      • Rebase for Formatting (then throw away that filthy offset aware datetime object)
    • Emil Mikulik on time
      • UTC vs UT1 vs UNIX time
      • Timezones are a presentation-layer problem!
    • Getting timezone information: pytz vs python-dateutil
  • Na├»ve vs Aware datetimes
    • datetime.now(tz) vs datetime.utcnow()
    • What does tm_isdst actually mean
    • datetime vs struct_time vs UNIX time
  • How to store them?
    • Using UNIX time: time.gmtime() and calendar.timegm()
    • Using MySQL (date, datetime, timestamp)
    • Using Postgres (date, timestamp)
    • Using Sqlite (text, real, integer)
    • To talk to JavaScript
  • Formatting with offsets
    • strftime and %z and friends, e.g. to simulate syslog log lines