Should I avoid date.today() in favor of timezone-aware datetimes?
Asked by
MellowPine47
A recent Ruff version warns about using `date.today()` and suggests getting the current date through something like `datetime.now(ZoneInfo(...))` instead. Is this because naive dates are effectively deprecated due to timezone concerns, or is the rule too broad? I work with financial data and Excel spreadsheets, including bond maturity dates. These are calendar dates rather than moments in time, and Excel does not support timezone-aware datetimes. Adding timezones would either cause export errors or add unnecessary conversions, so I'm unsure how to handle these warnings appropriately.
Answers
The practical rule is to model the meaning of the value rather than blindly making everything timezone-aware. Use aware datetimes or UTC for events that happen at a particular instant. Use `date` for calendar concepts that are intentionally timezone-independent. For `today`, being explicit can still be useful when the business definition depends on a particular location, but for a quick local log message, `date.today()` is perfectly understandable. Ruffโs recommendation is a useful warning for ambiguous datetime code, not proof that every use of `date.today()` is wrong.
Reply to this answer
For Excel, keep the boundary explicit. Excel serial dates and datetimes are timezone-naive, and libraries such as `openpyxl` reject timezone-aware values. If the source value is a calendar date, use `datetime.date` or a naive datetime only at the Excel/import-export boundary, and consider suppressing or configuring the Ruff rule for those specific lines. Converting a maturity date to a timezone-aware datetime does not add useful information if no time or timezone was present in the source.
Reply to this answer
The warning comes from Ruffโs `DTZ011` rule, not from an official deprecation of `date.today()`. The rule reflects a legitimate concern: naive datetimes are easy to misuse when they represent actual moments in time. For timestamps, transactions, creation times, and similar values, use an aware datetime or a UTC timestamp and convert only for display. But a `date` representing a calendar dayโsuch as a bond maturity date, invoice due date, or recurring scheduleโis a different concept and does not inherently need a timezone.
QuietHarbor21: That distinction is important. A date-only value should not need to be turned into midnight in some arbitrary timezone just to satisfy a linter.
Reply to this answer
Add your answer
Answers are reviewed before publication.
BrightCactus32: Exactly. Adding a timezone and then stripping it before writing to Excel would mostly create extra code without improving the meaning of the data.