2

I am trying to match time zones with empty string in strptime function. Howevr, I get the following error.

ValueError: time data 'Thu Apr 14 01:46:29 MDT 2016' does not match format '%a %b %d %H:%M:%S   %Y'

This is the code I try.

import datetime

d = datetime.datetime.strptime('Thu Apr 14 01:46:29 MDT 2016', '%a %b %d %H:%M:%S   %Y')

How to map time-zone in python? time zone can be MDT, MST,etc.

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
newday
  • 3,842
  • 10
  • 54
  • 79
  • No, all text must be matched. Either remove the timezone characters, or match them as literals with `'%a %b %d %H:%M:%S MDT %Y'` – Martijn Pieters May 16 '16 at 21:06
  • 1
    It should be `%Z` for that, but the parser doesn't seem to recognize anything but UTC. Even EST and CST, the examples in the [documentation](https://docs.python.org/3.5/library/datetime.html#strftime-and-strptime-behavior), produce an error. – TigerhawkT3 May 16 '16 at 21:06
  • @Martjin as I mentioned in the question, time-zone can be changed and I don't want to remove time-zone. – newday May 16 '16 at 21:09
  • @Tigerhawk, I tried empty string but still it produces error. – newday May 16 '16 at 21:10
  • @TigerhawkT3 sort of a duplicate, but MDT is also not supported http://stackoverflow.com/questions/15447706/convert-string-to-time-with-python – David May 16 '16 at 21:11
  • 1
    Check out this http://stackoverflow.com/questions/1703546/parsing-date-time-string-with-timezone-abbreviated-name-in-python – David May 16 '16 at 21:12
  • @newday, are your input timezones limited to a few that you know of? – Padraic Cunningham May 16 '16 at 21:12
  • to the moment it is MST and MDT. – newday May 16 '16 at 21:18
  • My concern is why two out of the three examples in the official documentation don't work. – TigerhawkT3 May 16 '16 at 21:19
  • 1
    Try this.` x = "Thu Apr 14 01:46:29 MDT 2016"` `d = datetime.datetime.strptime(x, '%a %b %d %H:%M:%S {} %Y'.format(x.split()[-2]))` Not sure this will solve your problem ;) – Anoop May 16 '16 at 21:20
  • @newday Is it working for you? – Anoop May 16 '16 at 21:46

1 Answers1

1

To parse this specific format (similar to rfc 822 used in emails), you could use email packages:

from email.utils import parsedate_tz, mktime_tz

time_tuple = parsedate_tz('Thu Apr 14 01:46:29 MDT 2016')
posix_time = mktime_tz(time_tuple)

Note: MDT is -6 hours here (according to the rfc 822). In general, timezone abbreviations may be ambiguous.

On Python 3.3+, you could create a timezone-aware datetime directly:

from email.utils import parsedate_to_datetime

dt = parsedate_to_datetime('Thu Apr 14 01:46:29 MDT 2016')

Here's how to parse it on earlier Python versions.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670