5

I am trying to simply create a datetime object from the following date: 'Fri Mar 11 15:59:57 EST 2016' using the format: '%a %b %d %H:%M:%S %Z %Y'.

Here's the code.

from datetime import datetime
date = datetime.strptime('Fri Mar 11 15:59:57 EST 2016', '%a %b %d %H:%M:%S %Z %Y')

However, this results in a ValueError as shown below.

ValueError: time data 'Fri Mar 11 15:59:57 EST 2016' does not match format '%a %b %d %H:%M:%S %Z %Y'

Maybe I am missing something obviously wrong with my format string, but I have checked it over and over. Any help would be greatly appreciated, thanks.

Edit to reflect comments/questions for more information:

The Python version I'm using is 2.7.6.

Using the 'locale' command on Ubuntu 14.04 I get this:

$ locale
LANG=en_US.UTF-8
LANGUAGE=
LC_CTYPE="en_US.UTF-8"
LC_NUMERIC="en_US.UTF-8"
LC_TIME="en_US.UTF-8"
LC_COLLATE="en_US.UTF-8"
LC_MONETARY="en_US.UTF-8"
LC_MESSAGES="en_US.UTF-8"
LC_PAPER="en_US.UTF-8"
LC_NAME="en_US.UTF-8"
LC_ADDRESS="en_US.UTF-8"
LC_TELEPHONE="en_US.UTF-8"
LC_MEASUREMENT="en_US.UTF-8"
LC_IDENTIFICATION="en_US.UTF-8"
LC_ALL=
  • 2
    I tried your code and it works for me; what version of Python are you using? – Peter Wang Jul 04 '16 at 17:43
  • I'm using Python 2.7.6 – Jonathan Freed Jul 04 '16 at 17:45
  • Are you by any chance using a computer which uses a non-English locale setting? – Maximilian Peters Jul 04 '16 at 17:47
  • Here's the output of the 'locale' command. This is on ubuntu 14.04 on Amazon AWS by the way. $ locale LANG=en_US.UTF-8 LANGUAGE= LC_CTYPE="en_US.UTF-8" LC_NUMERIC="en_US.UTF-8" LC_TIME="en_US.UTF-8" LC_COLLATE="en_US.UTF-8" LC_MONETARY="en_US.UTF-8" LC_MESSAGES="en_US.UTF-8" LC_PAPER="en_US.UTF-8" LC_NAME="en_US.UTF-8" LC_ADDRESS="en_US.UTF-8" LC_TELEPHONE="en_US.UTF-8" LC_MEASUREMENT="en_US.UTF-8" LC_IDENTIFICATION="en_US.UTF-8" LC_ALL= – Jonathan Freed Jul 04 '16 at 17:50
  • In short, to answer your question, no. It appears the locales are all set to en_US – Jonathan Freed Jul 04 '16 at 17:53
  • Don't know how if your AWS instance is really precious, but you could try `sudo timedatectl set-timezone EST` – Maximilian Peters Jul 04 '16 at 17:59

1 Answers1

11

For the %Z specifier, strptime only recognises "UTC", "GMT" and whatever is in time.tzname (so whether it recognises "EST" will depend on the time zone of your computer). This is issue 22377.

See:

The best option for parsing timezones that include a human-readable time zone is still to use the third-party python-dateutil library:

import dateutil
date = dateutil.parse('Fri Mar 11 15:59:57 EST 2016')

If you cannot install python-dateutil, you could strip out the timezone and parse it manually e.g. using a dictionary lookup.

Nazim Kerimbekov
  • 4,712
  • 8
  • 34
  • 58
ecatmur
  • 152,476
  • 27
  • 293
  • 366