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

1

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

2 Comments

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.
@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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.