我正在尝试将a解析str
为一个datetime.datetime
对象。但是,我无法实现这一点,因为时区为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'
我怎样才能解决这个问题?
有两种方法可以解决此问题:
将字符串中的GST替换为UTC
用适当的时间转换将字符串中的GST替换为UTC(将UTC中的时间减少4小时,因为GST 时间比UTC +4小时)。
方法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')
方法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)