python / cpython

The Python programming language
https://www.python.org
Other
63.03k stars 30.19k forks source link

Add aliases with explicit names for naive and aware datetime.now() and utcnow() #103377

Open vashek opened 1 year ago

vashek commented 1 year ago

Feature or enhancement

I propose adding the following class methods to datetime.datetime:

Pitch

It is currently not very obvious that datetime.now() and datetime.utcnow() return naive datetime objects. In fact, arguably datetime.utcnow() is misleading as one might expect it to return time with the UTC timezone.

It is also not very obvious how to obtain the aware versions. (At least, it's not to me; I find myself looking it up repeatedly.)

These aliases make it very obvious which version is returned and would be easily discoverable.

Previous discussion

A thread is open at https://discuss.python.org/t/add-aliases-with-explicit-names-for-naive-and-aware-datetime-now-and-utcnow/25997

A related idea was discussed at https://discuss.python.org/t/get-now-with-local-system-timezone-without-knowing-the-timezone-first/22665

Linked PRs

pganssle commented 1 year ago

I am -1 on this:

  • localnow_naive() as an alias to now()

I'm not sure people will discover this or that it would be obvious what it does and why. It particularly doesn't make sense without the other three.

  • localnow_aware() as an alias to now().astimezone()

This is only pseudo-aware and I don't think we should be encouraging people to do this by default. I think they'll think that they are getting a proper aware time zone (like one with a ZoneInfo object), and not realize that they are effectively doing the same thing as pytz.timezone(my_timezone).localize(datetime.now()), which won't work properly with arithmetic. The proper way to work with local times is to keep them naïve until you need to access utcoffset or tzname.

  • utcnow_naive() as an alias to utcnow()

We should deprecate utcnow.

  • utcnow_aware() as an alias to now(timezone.utc)

This is the one I'm most sympathetic to, but also I think that it's only useful when people are expecting to find a utcnow method, and as I mentioned above I think we can deprecate it. I think datetime.now(UTC) is a perfectly reasonable pattern.