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

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 to now()
  • localnow_aware() as an alias to now().astimezone()
  • utcnow_naive() as an alias to utcnow()
  • utcnow_aware() as an alias to now(timezone.utc)

I actually have a pull request open for this, but I need some feedback. Here’s the PR:

What do you think?

3 Likes

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.

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.

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.

4 Likes

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.