Member-only story
Python’s datetime in a Nutshell
Many find the datetime module hard to grok. However, when you condense the explanations into clear and simple parts with examples, the datetime module is powerful and easy to use!
I use dates and times in my astronomical, solar energy, archaeoastronomy, and other calculations all the time. With Visual Basic, javascript, and other programming languages it was easy to do, but something about Python’s datetime module threw me for a loop. I tried Arrow and other alternatives, but once I studied datetime to the point where I could explain it “in a nutshell”, it turned out to be easy to get a handle on. I hope this article helps you too.
Why datetime.datetime?
I think someone messed up with the naming of this module and class! A little clarification is in order.
You’ll see datetime imported in several different ways. Here’s the easiest approach to importing it, although your code after the import can get a little long-winded when you do it this way.
import datetimewhen = datetime.datetime.now()
print(when)# 2022-05-04 11:13:44.914477
Notice that the module named datetime is imported, but the object named datetime within the module is accessed with the datetime.datetime() method. This can be confusing, especially when you notice that the datetime class does not follow the Python standard of uppercasing its first letter!