Parsing and Normalizing Dates with Timezones in Python

This was a bit painful and not well documented, so documenting here for future reference.

Say you want to parse and normalize dates with timezones (eg. dates in email headers, I believe based on rfc822). Here’s what you do:

Install pytz.


import email, time, datetime
import pytz
utctimestamp = email.Utils.mktime_tz(email.Utils.parsedate_tz( msg['Date'] ))
utcdate= datetime.datetime.fromtimestamp( utctimestamp, pytz.utc )
pacificdate = utcdate.astimezone(pytz.timezone('US/Pacific'))

parsedate_tz produces a tuple that can be digested by mktime_tz, which in turn spits out a timestamp based on the UTC timezone. You can turn this into a datetime via fromtimestamp and set its timezone to UTC. Once you have the TZ aware datetime you can manipulate it to your heart’s content; the final line above converts it to a US/Pacific date.

Full example:


>>> import email, time, datetime
>>> import pytz
>>> date_eastern = 'Thu, 31 Jan 2008 17:56:13 -0500'
>>> utctimestamp = email.Utils.mktime_tz(email.Utils.parsedate_tz( date_eastern ))
>>> utcdate= datetime.datetime.fromtimestamp( utctimestamp, pytz.utc )
>>> utcdate
datetime.datetime(2008, 1, 31, 22, 56, 13, tzinfo=<UTC>)
utcdate.astimezone(pytz.timezone('US/Pacific'))
datetime.datetime(2008, 1, 31, 14, 56, 13, tzinfo=<DstTzInfo 'US/Pacific' PST-1 day, 16:00:00 STD>)

9 Comments so far

  1. Brad Grantham on February 25th, 2008

    Thanks! Just what I needed as I’m trying to break 15 years of email messages into buckets by year.
    -Brad

  2. hamdi on August 23rd, 2008

    I can’t say that i really understand your code but i want to ask if it is possible to convert python datetime.datetime to rfc822 format. i mean : i have 2008-08-19 11:38:51.035000 but i want sth like : Wed, 02 Oct 2007 13:00:00 GMT

  3. Parand on August 23rd, 2008

    Hamdi, you can use sprintf:

    from datetime import datetime
    datetime.now().strftime(”%a, %d %b %Y %H:%M:%S %Z”)
    ‘Sat, 23 Aug 2008 15:39:12 ‘

  4. hamdi on August 24th, 2008

    Thanks. That’s it :)

  5. Tim on August 31st, 2009

    Thank you so much! Very helpful. :-)

  6. Coops on April 7th, 2010

    Really useful post – been stuck on this for a few hours!

  7. [...] first serious project in python. I’d also like to give some thanks to an excellent blog post found here, which addresses the issue of handling timezones in python (something that is surprisingly [...]

  8. dbarua on April 26th, 2011

    Thanks a lot.

  9. kailash on July 14th, 2011

    How to convert
    datetime.datetime(2008, 1, 31, 14, 56, 13, tzinfo=)
    into seconds ??

Leave a Reply