Python: how I import the datetime module

Python’s datetime module risks a whole bunch of name confusion:
- It contains a class also called
datetime. When you read the worddatetime, you can’t be sure it’s the module or the class. - It contains a
timeclass. This can be confused with thetimemodule, or thetimemodule’stime()function. - It contains a class called
timezone. In a Django project this can be confused with thedjango.utils.timezonemodule.
For these reasons, I use this import idiom and recommend you do too:
import datetime as dt
Rather than any of:
import datetime
from datetime import datetime # or time, timezone
Then in your code, dt.datetime, dt.time, and dt.timezone will be unambiguous.
😸😸😸 Check out my new book on using GitHub effectively, Boost Your GitHub DX! 😸😸😸
One summary email a week, no spam, I pinky promise.
Related posts: