Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Python, how can I turn this format into a unix timestamp?

Tags:

python

date

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:

https://api.twitter.com/1/statuses/user_timeline.json?include_entities=true&include_rts=true&screen_name=twitter

like image 545
TIMEX Avatar asked Jul 09 '12 20:07

TIMEX


1 Answers

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)))
like image 199
ThiefMaster Avatar answered Oct 06 '22 08:10

ThiefMaster