0

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.

bigblind
  • 12,539
  • 14
  • 68
  • 123
  • What's your time zone? – Psytho Jan 30 '16 at 18:28
  • I'm in UTC+1. Using parsedate_tz doesn't work either. It returns a timezone offset as an extra element in the tuple, but doesn't impact the rest of the tuple. So there's probably a conversion to local time happening somewhere, but I have no clue where. – bigblind Jan 30 '16 at 18:29
  • Maybe the `email.parsedate` function treats `GMT` as a time zone, and includes Daylight saving time? In general I would avoid mixing several different modules like you do here (email, time and datetime). `pytz` is a very good package for dealing with time and timezones. – Håken Lid Jan 30 '16 at 18:45
  • The problem is that time.mktime expects the time tuple to be in local time. Thanks for all your help. – bigblind Jan 30 '16 at 18:50
  • http://stackoverflow.com/questions/15447632/python-convert-utc-time-tuple-to-utc-timestamp – Padraic Cunningham Jan 30 '16 at 18:52

4 Answers4

1

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

bigblind
  • 12,539
  • 14
  • 68
  • 123
0

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")
Boaz
  • 4,864
  • 12
  • 50
  • 90
0

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
nsilent22
  • 2,763
  • 10
  • 14
0

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)
Juraj Bezručka
  • 512
  • 5
  • 21