0

I am trying to parse a str as a datetime.datetime object. However, I am unable to achieve this because the timezone is GST.

import datetime s_dt = 'Mon Jul 01 17:17:37 UTC' datetime.datetime.strptime(s_dt, '%a %b %d %H:%M:%S %Z') # datetime.datetime(1900, 7, 1, 17, 17, 37) s_dt = 'Mon Jul 01 17:17:37 GST' datetime.datetime.strptime(s_dt, '%a %b %d %H:%M:%S %Z') # ValueError: time data 'Mon Jul 01 17:17:37 GST' does not match format '%a %b %d %H:%M:%S %Z' 

How can I fix this?

1 Answer 1

1

There are two ways to deal with this:-

  1. Replace the GST in the string, to UTC

  2. Replace the GST in the string, to UTC with proper time conversion (decreasing the time in UTC by 4 hours, as time GST is +4 hours from UTC).

METHOD 1:-

s_dt = 'Mon Jul 01 17:17:37 GST'.replace("GST", "UTC") datetime.datetime.strptime(s_dt, '%a %b %d %H:%M:%S %Z') 

METHOD 2:-

# replacing GST to UTC in original string s_dt = 'Mon Jul 01 17:17:37 GST'.replace("GST", "UTC") # getting the hours from the string s_dt_obj = int(s_dt.split(":")[0][-2:]) # substracting 4 from the hours (in order to create UTC equivalent of GST time) s_dt_obj = str((s_dt_obj - 4) % 24) # putting everything back to a string s_dt_obj = f"{s_dt.split(':')[0][:-2]}{s_dt_obj}:{s_dt.split(':')[1]}:{s_dt.split(':')[2]}" # creating datetime object out of our newly created string datetime.datetime.strptime(s_dt_obj, '%a %b %d %H:%M:%S %Z') # datetime.datetime(1900, 7, 1, 13, 17, 37) 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.