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:
- It removes the ambiguity of
datetime
being the module or the class:- If you know the convention, you know that
dt
is the module anddt.datetime
is the class. - If you don't know the convention, and see code using it, it's intuitive to figure out that
dt.datetime
is the class and not the module. Worst case, you will check the import statement to confirm that, as it's a pattern you haven't seen before. - If you don't know the convention, and want to use
datetime
on a file where the proposed form is used, you won't accidentally just usedatetime
because it's not imported asimport datetime
orfrom datetime import datetime
(I am assuming here that your IDE would warn you of undefined names/variables). That will force you to go to the import section and discover that it's usingimport datetime as dt
.
- If you know the convention, you know that
- It frees the namespace to use
datetime
anddate
as variables. But be careful with that! Make sure you are using it on a small scope where another developer can see without scrolling that they are defined variables. Otherwise, there is the possibility of somebody not paying attention try to use them as the module or the class. - It's more beautiful than
datetime.datetime
:D
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!