Avoiding common pitfalls of datetime from a webapp's perspective

Indradhanush Gupta (~indradhanush)




The datetime module is easily one of the most used standard libraries of Python. Yet, most of us struggle using it without hitting a snag or two, especially when one has to take care of multiple timezones. This talk is aimed at identifying such snags and how to fix them.

This talk is divided into 2 parts. Part 1 deals with the datetime library itself, wherein the audience will get to know about the basic datetime types and common issues that crop up when dealing with datetimes across multiple timezones. It will also demonstrate the idea from a webapp's perspective. That is, how Postgres plays along with your webapp via Django. Knowledge of django is not a requirement as the same rules apply for any other web framework out there. It will be used just to explain the point in a more realistic context.

Part 2 will deal with writing tests that depend on a specific time, for example, deleting all auth tokens older than 3 days.

Introduction (2 min)

Part 1 (20 min)

  1. Naive vs Aware datetimes (4 min)
  2. Avoiding common pitfalls of datetime conversion and storage - Usepytz instead of datetime.datetime.replace (6 min)
  3. Use cases and examples in a production environment [Postgres + Django] (10 min)
    • In this I will focus about the use case where a user wants to filter out data based on some time range. It is easy to ignore the timezone of the user and end up returning data assuming that the user is in the same time zone as the service itself.
    • Also, what happens when you create a datetime object in bare Python (both naive and aware) and decide to store it in a database, in this case Postgres.

Part 2 (7 min)

  1. Using freezegun to simulate the current time in your tests instead of mocking the datetime library. (3 min)
  2. Examples (4 min)

If time permits the following will also be discussed:

  1. timedelta
  2. dateutil.relativedelta
  3. dateutil.parser

Q&A (10 min)


Basic familiarity with Python and the datetime module.

Content URLs:

Have already written a blog post related to Part 1 of the Talk: http://indradhanush.github.io/2015/03/23/dealing-with-datetime-objects-in-python/

Any scripts used in the talk will be made available at Github.

Final Slides: http://indradhanush.github.io/talks/pycon-india-15/slides.html

Speaker Info:

Currently working at Instamojo, the speaker was selected and successfully completed the Google Summer of Code 2014.

The speaker loves the field of Networking and wants to learn about internet security. Some technologies he likes to play around with are:

  • ZeroMQ
  • Twisted
  • Django
  • Golang

Speaker Links:

  • Blog: http://indradhanush.github.io
  • Github: http://github.com/indradhanush
  • Twitter: http://twitter.com/indradhanush92
  • IRC: dhanush on irc.freenode.net

Section: Core Python
Type: Talks
Target Audience: Beginner
Last Updated: