Why does datetime.datetime.utcnow() not contain timezone information?

前端 未结 9 1079
南方客
南方客 2020-11-29 16:12
datetime.datetime.utcnow()

Why does this datetime not have any timezone info given that it is explicitly a UTC datetime?<

9条回答
  •  醉话见心
    2020-11-29 17:09

    The pytz module is one option, and there is another python-dateutil, which although is also third party package, may already be available depending on your other dependencies and operating system.

    I just wanted to include this methodology for reference- if you've already installed python-dateutil for other purposes, you can use its tzinfo instead of duplicating with pytz

    import datetime
    import dateutil.tz
    
    # Get the UTC time with datetime.now:
    utcdt = datetime.datetime.now(dateutil.tz.tzutc())
    
    # Get the UTC time with datetime.utcnow:
    utcdt = datetime.datetime.utcnow()
    utcdt = utcdt.replace(tzinfo=dateutil.tz.tzutc())
    
    # For fun- get the local time
    localdt = datetime.datetime.now(dateutil.tz.tzlocal())
    

    I tend to agree that calls to utcnow should include the UTC timezone information. I suspect that this is not included because the native datetime library defaults to naive datetimes for cross compatibility.

提交回复
热议问题