Mon Jul 09 09:20:28 +0000 2012
If I have a format like that as a STRING, how can I turn it into a unix timestamp?
Note: I'm getting this format from Twitter's API:
Mon Jul 09 09:20:28 +0000 2012
If I have a format like that as a STRING, how can I turn it into a unix timestamp?
Note: I'm getting this format from Twitter's API:
The best option is using dateutil.parser.parse()
which gives you a datetime
object with proper timezone information:
>>> import dateutil.parser
>>> dt = dateutil.parser.parse('Mon Jul 09 09:20:28 +0200 2012')
>>> dt
datetime.datetime(2012, 7, 9, 9, 20, 28, tzinfo=tzoffset(None, 7200))
Now you just need to convert it to a UNIX timestamp:
>>> import time
>>> int(time.mktime(dt.timetuple()))
1341822028
The format you have can also be easily parsed using email.utils.parsedate_tz
:
>>> import datetime
>>> import email.utils
>>> parts = email.utils.parsedate_tz('Mon Jul 09 09:20:28 +0200 2012')
>>> dt = datetime.datetime(*parts[:6]) - datetime.timedelta(seconds=parts[-1])
>>> str(dt)
'2012-07-09 07:20:28'
This is actually how email.utils.parsedate_to_datetime
in Python 3.3 is implemented (if you want to copy&paste this into your project, replace __parsedate_tz
with parsedate_tz
from email.utils
):
def parsedate_to_datetime(data):
if not data:
return None
*dtuple, tz = __parsedate_tz(data)
if tz is None:
return datetime.datetime(*dtuple[:6])
return datetime.datetime(*dtuple[:6],
tzinfo=datetime.timezone(datetime.timedelta(seconds=tz)))
If the timezone is known to be always +0000, you can use:
time.strptime('Mon Jul 09 09:20:28 +0000 2012', '%a %b %d %H:%M:%S +0000 %Y')
This returns a datetime structure. If you need unix seconds since epoch, run through time.mktime(), like this:
>>> time.mktime(time.strptime('Mon Jul 09 09:20:28 +0000 2012', '%a %b %d %H:%M:%S +0000 %Y'))
1341818428.0
or time.gmtime() if indeed the timezone is always UTC.
datetime.strptime()
Reference: http://docs.python.org/library/time.html#time.strptime