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

前端 未结 9 1083
南方客
南方客 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 16:54

    The standard Python libraries don't include any tzinfo classes (but see pep 431). I can only guess at the reasons. Personally I think it was a mistake not to include a tzinfo class for UTC, because that one is uncontroversial enough to have a standard implementation.

    Edit: Although there's no implementation in the library, there is one given as an example in the tzinfo documentation.

    from datetime import timedelta, tzinfo
    
    ZERO = timedelta(0)
    
    # A UTC class.
    
    class UTC(tzinfo):
        """UTC"""
    
        def utcoffset(self, dt):
            return ZERO
    
        def tzname(self, dt):
            return "UTC"
    
        def dst(self, dt):
            return ZERO
    
    utc = UTC()
    

    To use it, to get the current time as an aware datetime object:

    from datetime import datetime 
    
    now = datetime.now(utc)
    

    There is datetime.timezone.utc in Python 3.2+:

    from datetime import datetime, timezone 
    
    now = datetime.now(timezone.utc)
    

提交回复
热议问题