I have this readout Tue, 19 Jan 2016 16:12:18 -0800 (PST)
I'm storing emails in mongo and I'd like to convert this into a python time object so I can query Mongo based on time of the email.
What is the best way to do this?
Thanks!
I have this readout Tue, 19 Jan 2016 16:12:18 -0800 (PST)
I'm storing emails in mongo and I'd like to convert this into a python time object so I can query Mongo based on time of the email.
What is the best way to do this?
Thanks!
python-dateutil
would make things simple:
>>> from dateutil.parser import parse
>>> parse("Tue, 19 Jan 2016 16:12:18 -0800 (PST)")
datetime.datetime(2016, 1, 19, 16, 12, 18, tzinfo=tzoffset(u'PST', -28800))
One way is to use the strptime functionality of the datetime module,
i.e.
import datetime
timestamp = "Tue, 19 Jan 2016 16:12:18 -0800 (PST)"
dt = datetime.datetime.strptime(timestamp, "%a, %d %b %Y %H:%M:%S %z (%Z)")
Please read up on Python's datetime module for find the guide about how these format strings work specifically so that you can build your own!
To parse a time string from an email, you could use email
package from stdlib:
>>> from email.utils import parsedate_tz, mktime_tz
>>> timestamp = mktime_tz(parsedate_tz('Tue, 19 Jan 2016 16:12:18 -0800 (PST)'))
where timestamp
is "seconds since the Epoch". To get UTC time which you can pass to MongoDB:
>>> from datetime import datetime, timedelta
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> utc_time
datetime.datetime(2016, 1, 20, 0, 12, 18)
Python 3.2+
from datetime import datetime
datetime.strptime("Tue, 19 Jan 2016 16:12:18 -0800 (PST)"[:31],
'%a, %d %b %Y %H:%M:%S %z')