Mastodon

How I started to import datetime module in Python

by Dmytro Litvinov

How I started to import datetime module in Python

Share

Most of web projects where I work requires manipulation with date and for that Python has a great builtin module called datetime.

And just because I manage awesome flake8 extensions I never used in my projects a great extension called flake8-datetime-import before today. It enforces importing datetime as dt and time as tm

I always felt that mess in my projects. The rationale is very well explain at repo:

# Bad
import datetime
from datetime import datetime, time, timezone

import time
from time import time, timezone

Consistently importing and aliasing the datetime and time modules helps prevent this ambiguity.

# Good
import datetime as dt
import time as tm

dt.datetime.now()
tm.time()

P.S. Since I started to use ruff at my daily work there is no direct support for plugin (already asked question at repo), but what you can do is next:

[tool.ruff.lint.flake8-import-conventions.extend-aliases]
"datetime" = "dt"
"time" = "tm"

[tool.ruff.lint.flake8-import-conventions]
banned-from = ["datetime", "time"]

P.P.S. I would appreciate if you can go to awesome flake8 extensions repo and just give a Star at GitHub ⭐