Python - simplest and most coherent way to get timezone-aware current time in UTC?

前端 未结 3 1064
清歌不尽
清歌不尽 2020-12-10 23:10

datetime.now() doesn\'t appear to have timezone info attached. I want the current time in UTC. What do I do?

>>> from datetime import         


        
相关标签:
3条回答
  • 2020-12-10 23:29

    I use pytz

    Then use the following bit of code

    import pytz
    from datetime import datetime
    now = datetime.utcnow().replace(tzinfo = pytz.utc)
    
    0 讨论(0)
  • 2020-12-10 23:41

    In Python 3:

    datetime.now(timezone.utc)
    

    In Python 2.x there is no timezone object, but you can write your own:

    try:
        from datetime import timezone
    except ImportError:
        from datetime import tzinfo, timedelta
    
        class timezone(tzinfo):
            def __init__(self, utcoffset, name=None):
                self._utcoffset = utcoffset
                self._name = name
    
            def utcoffset(self, dt):
                return self._utcoffset
    
            def tzname(self, dt):
                return self._name
    
            def dst(self, dt):
                return timedelta(0)
    
        timezone.utc = timezone(timedelta(0), 'UTC')
    

    Then you can do datetime.now(timezone.utc) just like in Python 3.

    0 讨论(0)
  • 2020-12-10 23:47

    Use datetime.utcnow() for the current time in UTC.

    Adapting from this answer, here is how to make the object timezone-aware.

    >>> import pytz
    >>> from datetime import datetime
    >>> datetime.now(pytz.utc)
    datetime.datetime(2014, 3, 11, 15, 34, 52, 229959, tzinfo=<UTC>)
    
    0 讨论(0)
提交回复
热议问题