Should I avoid date.today() in favor of timezone-aware datetimes?

0
5
Asked By MellowPine47 On

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.

3 Answers

Answered By CedarFox8 On

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.

Answered By IvoryLamp6 On

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.

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.

Answered By NorthwindMica5 On

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.

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.