flake8-datetime-import is an opinionated plugin which aims to reduce
confusing or inconsistent usage of Python's datetime module. It checks that
datetime and time are imported as modules and aliased like:
import datetime as dt
import time as tmpip install flake8-datetime-import| Code | Description |
|---|---|
| DTI100 | from datetime import ... is not allowed. datetime must be imported as a module. |
| DTI101 | datetime imported without aliasing as dt. Expected import datetime as dt. |
| DTI200 | from time import ... is not allowed. time must be imported as a module. |
| DTI201 | time imported without aliasing as tm. Expected import time as tm. |
datetime and time are confusing when encountered in code. Are they modules?
Are they classes or functions?
# Bad
import datetime
from datetime import datetime, time, timezone
import time
from time import time, timezoneConsistently 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()Importing and namespacing datetime prevents other naming collisions,
such as Django's django.utils.timezone:
import datetime as dt
from django.utils import timezone
dt.timezone.utc
timezone.now()This plugin was inspired by:
- A talk by @brandon-rhodes at PyCon Canada in which he mentioned this importing strategy
- Code review fatigue
Other notable mentions of this importing strategy:
To use with pre-commit, add flake8-datetime-import as an additional
dependency to flake8.
# .pre-commit-config.yml
- repo: https://github.com/pycqa/flake8
rev: 7.3.0
hooks:
- id: flake8
additional_dependencies: [
flake8-datetime-import,
]If you use ruff, you can enforce the same
convention without this plugin via
flake8-import-conventions.
Ban from datetime import ... / from time import ... and require the dt
and tm aliases:
# pyproject.toml
[tool.ruff.lint]
select = ["ICN"]
[tool.ruff.lint.flake8-import-conventions]
banned-from = [
"datetime", # Use `import datetime as dt`, not `from datetime import ...`
"time", # Use `import time as tm`, not `from time import ...`
]
[tool.ruff.lint.flake8-import-conventions.extend-aliases]
datetime = "dt"
time = "tm"