2

I am trying to parse the string '10/23/2019 6:02:05 PM EST' into a datetime with time zone using Python 3.7.

Code:

from datetime import datetime
timestamp = datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p %Z')

Error:

ValueError: time data '10/23/2019 6:02:05 PM EST' does not match format '%m/%d/%Y %I:%M:%S %p %Z'

When I create a datetime and output it using the same formatting I get the correct output. The only difference is that there is a 0 in front of the hour, but adding 0 in front of the 6 in my date string results in the same error.

My current solution is to parse the datetime without the timezone and then localize it, but this is not ideal.

date_lst = date.split()
date_str = ' '.join(date_lst[0:3])
timestamp = datetime.strptime(date_str, '%m/%d/%Y %I:%M:%S %p')
new_tz = pytz.timezone(date_lst[3])
timestamp_tz = new_tz.localize(timestamp)```
wjw
  • 209
  • 2
  • 6
  • It seems like this formatting works with UTC, but not other time zones (have tried EST, CST, IST) – wjw Oct 24 '19 at 10:27

2 Answers2

0

It is reasonable to expect that parsing a string with a timezone included would produce a timezone aware datetime object.

rtphokie
  • 609
  • 1
  • 6
  • 14
-1

Try it

>>timestamp = datetime.strptime('10/23/2019 6:02:05 PM EST', '%m/%d/%Y %I:%M:%S %p EST')

>>2019-10-23 06:02:05

You can try this.

Adam Strauss
  • 1,889
  • 2
  • 15
  • 45
  • This ignores the time zone and produces a time zone naive datetime, which will not error out (unless a time zone other than EST is input), but will also not pass the timestamp correctly because it is not passing the time zone. – wjw Oct 24 '19 at 13:34