How to convert string with timezone info to date in python

February 6, 2012 by
Filed under: python, troubleshooting 

In python, time.strftime() and time.strptime() can be used to format a date to string, and convert string to date. But it is thought buggy in the pyhon strptime() at 2.x version.

For example, if you invoke strptime(), It does not work as expected.

from datetime import datetime

dt='Sat Jan 28 12:27:31 +0800 2012';
datetime.strptime(dt,'%a %b %d %H:%M:%S %z %Y')

error shows as:  ValueError: ‘z’ is a bad directive in format ‘%a %b %d %H:%M:%S %z %Y’

Then how can we convert string with timezone information to date?For example, given a date string “Sat Jan 28 12:27:31 +0800 2012”, you need the represented date. You can take the convenient of email.utils like this on python 2.x:

import email.utils
from datetime import datetime

dt =u'Sat Jan 28 12:27:31 +0800 2012';

# parse the date string to several parts,
#  date_tz is a list: (2012, 1, 28, 12, 27, 31, 0, 1, -1, 28800)
date_tz = email.utils.parsedate_tz(dt);  

mydate=datetime(*date_tz[:6]);  # new a datetime by the first 6 elements of the list

Footnote: I checked  python 3.2, the strptime works in the first snippet. You may reference the “What’s new in python 3.2“.

Digg This
Reddit This
Stumble Now!
Vote on DZone
Share on Facebook
Bookmark this on Delicious
Share on LinkedIn
Bookmark this on Technorati
Post on Twitter
Google Buzz (aka. Google Reader)


Comments are closed.