Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Use of Deprecated utcnow() or utcfromtimestamp() APIs #161

Open
ShreyTiwari opened this issue Oct 29, 2024 · 0 comments
Open

Use of Deprecated utcnow() or utcfromtimestamp() APIs #161

ShreyTiwari opened this issue Oct 29, 2024 · 0 comments

Comments

@ShreyTiwari
Copy link

Hi there! 👋

I noticed that the codebase uses datetime.utcnow() or datetime.utcfromtimestamp(). These are deprecated and won't work with Python 3.12. They also handle naïve datetimes, which can lead to bugs. Could we switch to timezone-aware alternatives?

CodeQL Alerts

Here are the specific instances CodeQL flagged:

  1. date_now = datetime.datetime.utcnow()
  2. date_now = datetime.datetime.utcnow()
  3. date_now = datetime.datetime.utcnow()
  4. return datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
  5. timestamp=str(datetime.utcnow()),
  6. timestamp=str(datetime.utcnow()),
  7. else round_timestamp(datetime.utcnow(), "1D")
  8. return datetime.datetime.utcnow().replace(tzinfo=pytz.utc)

Explanation

Issue:

  • datetime.utcnow() and datetime.utcfromtimestamp() return naïve datetimes (without timezone info).
  • In Python 3, naïve datetimes are interpreted as system-local times, causing inconsistencies.
  • These methods are deprecated and no longer work in Python 3.12.

Example Problem:

from datetime import datetime
ts = 1571595618.0
x = datetime.utcfromtimestamp(ts)
x_ts = x.timestamp()
assert ts == x_ts, f"{ts} != {x_ts}" # Can fail in non-UTC locales

Recommended Solution:
Switch to time zone-aware methods:

from datetime import datetime, timezone
# Replace utcnow()
dt_now = datetime.now(tz=timezone.utc)
# Replace utcfromtimestamp()
ts = 1571595618.0
x = datetime.fromtimestamp(ts, tz=timezone.utc)
x_ts = x.timestamp()
assert ts == x_ts, f"{ts} != {x_ts}" # This succeeds

Action Required:

  • Replace all instances of datetime.utcnow() with datetime.now(tz=timezone.utc).
  • Replace all instances of datetime.utcfromtimestamp() with datetime.fromtimestamp(ts, tz=timezone.utc).

References:

For more details, see:

Thank you so much for your time and effort in maintaining this project! 🌟

Best,
Shrey

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant