3

I am trying to convert a string into date format in Python.

I am using following statement

datetime_obj = datetime.datetime.strptime("Sun Aug 19 16:24:31 PDT 2018", "%a %b %d %H:%M:%S %Z %Y")

However, I get an error -

ValueError: time data 'Sun Aug 19 16:24:31 PDT 2018' does not match format '%a %b %d %H:%M:%S %Z %Y'

If I remove the timezone from the date string and the format string, the code works perfect. Which leads me to believe that the issue is related to the timezone but I am not sure what actions should be taken. I am in eastern timezone and the time zone in the string is in Pacific timezone.

Appreciate any help on this.

Teoretic
  • 2,483
  • 1
  • 19
  • 28

1 Answers1

1

As mentioned in this answer you can use python-dateutil for this:

>>> from dateutil import parser

>>> datetime_obj = parser.parse("Sun Aug 19 16:24:31 PDT 2018")
datetime.datetime(2018, 8, 19, 16, 24, 31)

Standard datetime module behaves very strangely with parsing timezones, as I see reading this answer in question related to similar problem.

Teoretic
  • 2,483
  • 1
  • 19
  • 28