Add aliases with explicit names for naive and aware datetime.now() and utcnow() (original) (raw)
Hi all. Perhaps it’s my brain getting old, but I always forget if datetime.now()
and utcnow()
return a naive or aware datetime
object (it’s naive), and how to get the actual aware version. I’m not proposing any new improved way of handling timezones or anything like that: I’m just proposing aliases with hopefully very clear names that make it obvious what they do, and what the counterpart is called. Specifically, I propose adding the following class methods to datetime.datetime
:
localnow_naive()
as an alias tonow()
localnow_aware()
as an alias tonow().astimezone()
utcnow_naive()
as an alias toutcnow()
utcnow_aware()
as an alias tonow(timezone.utc)
I actually have a pull request open for this, but I need some feedback. Here’s the PR:
What do you think?
zware (Zachary Ware) April 19, 2023, 3:52pm 2
It seems to me that “naive” and “aware” would be confusing names to newcomers, who would likely need to get cozy with the documentation before understanding what they mean and how to use them.
For me, it’s straightforward enough that if you don’t ask for a timezone you don’t get one. I’ll admit that utcnow
has tripped me up before, though.
vashek (Vashek) April 19, 2023, 9:25pm 3
Hmm, how about:
datetime.now_local_with_timezone()
datetime.now_local_without_timezone()
datetime.now_utc_with_timezone()
datetime.now_utc_without_timezone()
I got used to it I suppose, but for me the opposite is true: I find it weird that the default is to get the “incomplete”, naive object.
hauntsaninja (Shantanu Jain) April 20, 2023, 4:51am 4
Maybe we should pursue the deprecation of utcnow
? I’m not seeing an issue for doing so on CPython, although it looks like it’s been off hand suggested a couple times, e.g. datetime.utcnow() should return a timezone aware datetime · Issue #90477 · python/cpython · GitHub
It does look very widely used, so would need to go a long, long time before it could be removed.
vashek (Vashek) April 20, 2023, 1:47pm 5
I’d be sympathetic to that, in fact I was considering suggesting it as part of this, I just thought I had better chance of getting agreement if I don’t mix in a proposal as controversial (I assume) as deprecating a widely used method.