python / typeshed

Collection of library stubs for Python, with static types
Other
4.29k stars 1.72k forks source link

Incorrect replacement for utcnow() #12328

Closed jkugler closed 3 weeks ago

jkugler commented 2 months ago

I have code such as this:

now_timestamp = datetime.utcnow()

The deprecation method reads:

The method "utcnow" in class "datetime" is deprecated
  Use timezone-aware objects to represent datetimes in UTC; e.g. by calling .now(datetime.UTC)

However, that is wrong on a couple counts. The correct call should be:

datetime.now(timezone.utc)

Code is here: https://github.com/python/typeshed/blob/6a9b53e719a139c2d6b41cf265ed0990cf438192/stdlib/datetime.pyi#L268 and here: https://github.com/python/typeshed/blob/6a9b53e719a139c2d6b41cf265ed0990cf438192/stdlib/datetime.pyi#L273

srittau commented 2 months ago

The error message is not incorrect, but a bit unprecise. datetime refers to the module, so datetime.UTC (which is an alias for datetime.timezone.utc) is indeed correct. But that's a bit confusing, as the error message previously talks about the class "datetime". (Edit: The error message is also lifted from CPython.)

srittau commented 2 months ago

Also, the error message is not guarded by a version_info block, but datetime.UTC is only available starting from Python 3.11, which makes it incorrect indeed in Python < 3.11. PR with a better message welcome!