0

I have a string like Apr-23-2018_10:57:19_EDT. Now I want to make a datetime object from it. I am using code in python 3 like below -

from datetime import datetime
datetime_object = datetime.strptime('Apr-23-2018_10:57:19_EDT', '%b-%d-%Y_%H:%M:%S_%Z')

And it is giving me error like below -

ValueError: time data 'Apr-23-2018_10:57:19_EDT' does not match format '%b-%d-%Y_%H:%M:%S_%Z'

Need help

  • Possible duplicate of [Python strptime() and timezones?](https://stackoverflow.com/questions/3305413/python-strptime-and-timezones) – BallpointBen May 06 '18 at 03:34

1 Answers1

1

Timezones are a mine field. If you can get away without it you can do something like:

Code:

datetime_object = dt.datetime.strptime(
    'Apr-23-2018_10:57:19_EDT'[:-4], '%b-%d-%Y_%H:%M:%S')
print(datetime_object)

Result:

2018-04-23 10:57:19
Stephen Rauch
  • 47,830
  • 31
  • 106
  • 135
  • Actually, I made a temporary implementation as you stated. But I want to know what is the reason behind this in brief. BTW, kudos for your great effort. – Tanvir Hossain Bhuiyan May 06 '18 at 04:39
  • @RazinTanvir, One big reason is that timezone strings are not unique. Additionally the libraries dealing with timezone parsing do not always have the same behavior. Result is that Python's ability to deal with them varies by platform and version. – Stephen Rauch May 06 '18 at 14:46