Remember to Import Your Datetime!

The datetime module is a powerful part of the Python standard library. However, some repetitive naming decisions make a simple syntactic import error common. This quick clarification can help avoid countless headaches!

Zack West
alpharithms

--

Image: alpharithms

Python’s Datetime module is a powerful addition to the standard library and helps make short work out of — you guessed it — managing dates and times. The syntax for importing the main Datetime class is a bit redundant and, in some cases, causes confusion.

To avoid AttributeError exceptions, one must ensure that the Datetime class is imported from the datetime module. Otherwise, one is left trying to import specific methods and functions from the module level vs. the class level where they actually reside.

Basic Datetime Example

Many of the useful functions in the datetime module are found within the Datetime class. These are accessed via standard dot-notation. Here’s an example of proper usage:

from datetime import datetime


# Create a datetime for now
now = datetime.now()

# View result
print(now, type(now))

2022-07-08 09:32:17.285837 <class 'datetime.datetime'>

# Create a formatted string version
timestamp =…

--

--

Zack West
alpharithms

Entrepreneur, programmer, designer, and lifelong learner. Can be found taking notes from Mother Nature when not hammering away at the keyboard.