简体   繁体   中英

1 hour off when converting RFC 2822 date to datetime

Here's what I'm trying to do:

>>> from email.utils import parsedate
>>> tup = parsedate("Fri, 22 Jan 2016 10:15:00 GMT")
>>> tup
(2016, 1, 22, 10, 15, 0, 0, 1, -1)
>>> import datetime
>>> import time
>>> timestamp = time.mktime(tup)
>>> timestamp
1453454100.0
>>> datetime.datetime.utcfromtimestamp(timestamp)
datetime.datetime(2016, 1, 22, 9, 15)

I'm using the email.utils.parsedate function to parse an RFC 2822 date to a struct_time. This looks correct, the hour part is 10 . Then, I convert it to a timestamp using time.mktime , and then, I try to get a UTC datetime out of it using datetime.utcfromtimestamp , but for some odd reason, the hour in the datetime is 9 . I don't really get why.

I'm in UTC+1, so there's probably a conversion to local time happening somewhere, but I have no clue where.

The problem is that mktime expects the tuple to be in local time. There's also calendar.gmtime , which expects it to be in UTC. I might actually just end up using dateutil as @Boaz recommends

I recommend just to use dateutil https://pypi.python.org/pypi/python-dateutil

It converts it directly to a correct datetime object

from dateutil import parser
parser.parse("Fri, 22 Jan 2016 10:15:00 GMT")

From Time access and conversions :

time.mktime(t):
This is the inverse function of localtime(). Its argument is the struct_time or full 9-tuple (since the dst flag is needed; use -1 as the dst flag if it is unknown) which expresses the time in local time, not UTC.

For correct results you should use calendar.timegm() :

>>> calendar.timegm(tup)
1453457700

You can also use datetime.

>>> from datetime import datetime as dt
>>> d = "Fri, 22 Jan 2016 10:15:00 GMT"
>>> dt.strptime(d, "%a, %d %b %Y %H:%M:%S %Z")
datetime.datetime(2016, 1, 22, 10, 15)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM