如何将 'HH:MM' 转换为 Python 的特定 GMT 时间?

How to convert 'HH:MM' to a particular GMT time on Python?

假设您有一个将以下时区格式存储为字符串类型的变量:

timezone = '(GMT -5:00)'

现在您有以下时间,设置为 GMT -4:00 时间且为字符串类型:

time1 = '4:00' #am  (GMT -4:00)
time2 = '9:00' #am  (GMT -4:00)

如何使用变量 timezonetime1time2 值更改为相应的本地时间?即:

time1 = '3:00' #am  (GMT -5:00)
time2 = '8:00' #am  (GMT -5:00)

想通了,它不是那么好,但它是诚实的工作:

import datetime

timezone = '(GMT -5:00)'
timezone = timezone.replace("(", "").replace("GMT ", "").replace(":","").replace(")", "")
gmt_hours = int(timezone[:2])

gmt_less_4_hours = -4

time_difference = abs(gmt_hours - gmt_less_4_hours)

time1 = "04:00" #am  (GMT -4:00)
time1 = datetime.datetime.strptime(time1, "%H:%M")
time1 -= datetime.timedelta(hours=time_difference)
time1 = time1.strftime('%H:%M')
print(time1)

time2 = '9:00' #am  (GMT -4:00)
time2 = datetime.datetime.strptime(time2, "%H:%M")
time2 -= datetime.timedelta(hours=time_difference)
time2 = time2.strftime('%H:%M')
print(time2)

输出:

03:00

08:00