温馨提示:本文翻译自stackoverflow.com,查看原文请点击:python - Parsing GST timezone with datetime.strptime
datetime python

python - 使用datetime.strptime解析GST时区

发布于 2020-03-27 11:09:22

我正在尝试将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'

我怎样才能解决这个问题?

查看更多

查看更多

提问者
Arjun
被浏览
69
Vasu Deo.S 2019-07-04 20:05

有两种方法可以解决此问题:

  1. 将字符串中的GST替换为UTC

  2. 用适当的时间转换将字符串中的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)