Best practice for importing the datetime module in Python

Posted on . Reading time: 3 mins. Tags: python.

The datetime module is one of the most controversial Python imports. That both the module and the class share the same name is unfortunate. I've seen many bugs caused by a developer using one thinking they are accessing the other because they didn't check how the import was done, and their IDE did not warn them.

The practice I've been putting in place with great success at the teams I've worked on is to use the following form:

import datetime as dt

# Examples of usage:
published_on = dt.datetime(2024, 2, 4, 22, 12)
today = dt.datetime.today()
five_seconds = dt.timedelta(seconds=5)

The benefits of this form are:

One could argue: well, if you are just going to adopt a convention and make sure the whole team uses it, why not stick to import datetime or from datetime import X? If everybody knows, it's fine!

The issue with that is existing code. If people have been mixing styles, you might open an old file, try to use datetime, see that is available in that namespace and wonder "Uh... is this already using the new convention"? On the other hand, if you find dt available on the namespace, it is almost guaranteed (unless somebody has been very creative with their imports) that the file is already using the convention.

All that said, nowadays, decent IDEs like PyCharm are able to figure out if you are working with the module or the class, making the whole post a bit of a moot point on some aspects. Still, consistency on coding is key, so if you don't adopt this form, at least consider choosing one for everybody on your team to use.

Happy coding!