Python datetime.utcnow() returning incorrect datetime

前端 未结 4 1861
渐次进展
渐次进展 2020-11-29 08:33
datetime.utcnow()

This call is returning an incorrect datetime, delayed from UTC/GMT by 1 hour (check in: http://www.worldtimeserver.com/current_ti

4条回答
  •  盖世英雄少女心
    2020-11-29 09:24

    Problem only occurs with utc time (Python3).

    e.g. System time:

    $ date
    
    Wed Jul 15 10:44:26 BST 2015
    

    Python time correct when using datetime.now():

    >>> datetime.now()
    
    datetime.datetime(2015, 7, 15, 10, 44, 30, 775840)
    

    ...But incorrect by one hour when using datetime.utcnow():

    >>> datetime.utcnow()
    
    datetime.datetime(2015, 7, 15, 9, 44, 32, 599823)
    

    UTC's problem is it doesn't know my timezone.

    You have to tell it, with the help of a timezone module called pytz:

    >>> import pytz
    >>> mytz = pytz.timezone('Europe/London')
    >>> pytz.utc.localize(datetime.utcnow(), is_dst=None).astimezone(mytz)
    
    datetime.datetime(2015, 7, 15, 11, 3, 43, 688681, tzinfo=)
    

    References:

    pytz - Converting UTC and timezone to local time

    https://opensourcehacker.com/2008/06/30/relativity-of-time-shortcomings-in-python-datetime-and-workaround/

    http://sweemengs-tech-world.blogspot.co.uk/2010/05/get-correct-datetime-value-for-python.html

    http://bugs.python.org/issue5094)

提交回复
热议问题