Warm tip: This article is reproduced from stackoverflow.com, please click
datetime python

Parsing GST timezone with datetime.strptime

发布于 2020-03-27 10:22:38

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?

Questioner
Arjun
Viewed
26
Vasu Deo.S 2019-07-04 20:05

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)