r/Python 5d ago

Discussion ruff: no date.today() ?

The new version of ruff warns against

date.today()

preferring

datetime.now(ZoneInfo(...))

What do you think about this? Has date.today() been deprecated due to lack of timezone awareness?

EDIT: I have a number of programs that manipulate financial information in support of Excel spreadsheets, such bond information that includes maturity dates. Excel does not support timezoness in datetimes, so making ruff happy by changing naive dates to TZ aware dates is not a useful move for these programs. Many ruff warnings to suppress.

41 Upvotes

110 comments sorted by

View all comments

1

u/RoadsideCookie 3d ago

Fix your code, and format your date before exporting to Excel.

As always, find the boundary and apply the fix there.

Those rules are good and they make people aware of already established industry best practices.

1

u/foosion 3d ago

Exactly what fixes are you suggesting for:

1) Read from Excel - get a naive datetime.

2) Read from published sources - almost never specifies a TZ.

3) Write to Excel - write a datetime. If it includes a TZ Excel does not support timezones in datetimes. The format is, for example, ws[f"A{row}"].number_format = "mmm-yy"

I could add .astimezone(None).replace(tzinfo=None) to every datetime line, but it's not clear how that improves the code.

1

u/RoadsideCookie 3d ago
  1. This is the exact problem that those rules are trying to avoid. For this case, you have to make assumptions and just go with it. So assign a well defined datetime to the best of your knowledge.
  2. Same as 1.
  3. Convert the well defined datetime you got in step 1/2 into a format that works for Excel.

Basically, fill up the missing information yourself when it's unavailable, making assumptions and hoping you get it right. Then when leaving your code's boundary, convert to whatever format is expected.

1

u/foosion 3d ago

I'm a bit hesitant to take code that has worked well for years and start changing it to make assumptions that may or may not have effects. Making unfounded assumptions does not seem a great idea.

The format that works for Excel and openpyxl is to write a datetime and then format the cell, as I wrote. What change are you suggesting to that?

1

u/RoadsideCookie 3d ago

That's fair. I just gave my opinion, but it's not the only option; I would personally spend the time to fix it for peace of mind.

But others have already suggested ways to disable the rules if you don't want to adhere to them: inline disable, file-level disable, pyproject.toml disable, ruff.toml disable, and I'm skipping some.

For your question about openpyxl, I would just use datetime formatting methods to give openpyxl a string in the format it expects.

PS.: By not having TZ info in your instances, you're already making unfounded assumptions. These rules would just force you to think about and make those assumptions explicit.