1

How can I convert a date string that looks like

2015-12-02 21:31:49 GMT

to a timestamp in Python 2?

NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
Tobi
  • 491
  • 1
  • 4
  • 8
  • 2
    Haven't you tried anything at all? – Paul Rooney Dec 03 '15 at 11:55
  • @Trilarion: This question has "with timezone" part. The answer depends on how the timezone is specified. – jfs Dec 03 '15 at 22:44
  • 1
    @J.F.Sebastian Thanks. What about [Python strptime() and timezones?](http://stackoverflow.com/questions/3305413/python-strptime-and-timezones) or [Parsing date/time string with timezone abbreviated name in Python?](http://stackoverflow.com/questions/1703546/parsing-date-time-string-with-timezone-abbreviated-name-in-python)? They seem to indicate that abbreviating the time zone and then wanting to parse that string is not a good idea anyway because the abbreviations are not unique. – NoDataDumpNoContribution Dec 04 '15 at 08:43

2 Answers2

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')
Community
  • 1
  • 1
NoDataDumpNoContribution
  • 10,591
  • 9
  • 64
  • 104
  • @J.F.Sebastian Thanks, I added the information. – NoDataDumpNoContribution Dec 04 '15 at 11:45
  • 1
    meta: this is one of the reasons why answering duplicate questions is bad: the knowledge such as whether and when `.strptime()` understands EST is not accumulated in a single place. Unless OP clarifies what kind of timezone abbreviations are expected in OP's application; the answers from a duplicate question should be used. – jfs Dec 04 '15 at 11:54
-1

try this:

import time
import datetime

ts = time.time()
timestamp = datetime.datetime.fromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S')
Aman Gupta
  • 1,764
  • 4
  • 30
  • 58