Search code examples
pythondatetimetimezoneutc

Easiest way to get a non-naive (aware) datetime of UTC now?


I was shocked to find that datetime.utcnow() returns a naive datetime object. What is the easiest way to get a non-naive (aware) datetime object of "now"? The only way I know to get that (pytz.utc.localize(datetime.utcnow())) seems to state the UTC aspect twice. Isn't there a more direct way?

I know it is not a very complex piece of code and therefore acceptable. But I'd like to understand why utcnow() doesn't return an aware object in the first place. After all the TZ of the result is known, so why not put it in the object?


Solution

  • The documentation suggests using datetime.now(timezone.utc).

    E.g.

    import datetime
    
    print(datetime.datetime.utcnow())
    # 2019-09-05 08:10:29.909459
    print(datetime.datetime.now(datetime.timezone.utc))
    # 2019-09-05 08:10:29.910137+00:00