The pitfalls of datetime¶
Python’s datetime module first appeared in Python 2.3, back in 2003.
That it has remained usable for over twenty years is remarkable, in a problem
domain this tricky: Java and JavaScript both ended up replacing their
date-time APIs wholesale, while Python never needed a wholesale replacement.
It does, however, have sharp edges which regularly trip up even experienced developers.
Below are the most impactful ones, and what whenever does instead.
Note
None of this is a condemnation of datetime. It has been carefully maintained
and adapted over the years—all while preserving backwards compatibility.
“Pitfall” is a subjective term: what follows is simply a catalog
of the places where the design makes certain mistakes easy to make.
One class for two incompatible concepts, so annotations can’t tell them apart
Eight hours after 10pm isn’t always 6am, but + thinks it is
Sometimes the system timezone, sometimes UTC, sometimes neither
Times that happen twice—or never—are resolved without a word
foldIdentical moments can compare unequal, and distinct ones equal
timezone isn’t a time zoneSeveral timezone classes to choose from; the obvious one is wrong
The result depends on your machine’s configuration
date inheritanceA subclass that can’t be compared with its own base class
timedelta.seconds footgunA remainder that looks like a total—right up until it doesn’t