How can I convert a date string that looks like
2015-12-02 21:31:49 GMT
to a timestamp in Python 2?
How can I convert a date string that looks like
2015-12-02 21:31:49 GMT
to a timestamp in Python 2?
Usually one would use datetime.strptime() or dateutil.parser.parse() but both ways do not work with timezones as abbreviations. They actually do not store the time zone info if an abbreviation is given (see Python strptime() and timezones? and Parsing date/time string with timezone abbreviated name in Python?).
The reason is that the abbreviations are not unique (EST is used both in North America and Australia) and therefore parsing a date string with time zone abbreviations is ambigous.
This means you cannot do the conversion reliably.
Additionally datetime.strptime()
may not recognize some time zone abbreviations like EST. It may recognize them if it is a local timezone.
However if by chance you anyway only ever have UTC/GMT, then just do
from datetime import datetime
date_string = '2015-12-02 21:31:49 GMT'
date = datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S %Z')
try this:
import time
import datetime
ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')