简体   繁体   中英

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

Suppose that you have a variable that stores the following time zone format as string type:

timezone = '(GMT -5:00)'

Now you have the following times, which were set in GMT -4:00 time and as string types:

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

How can be used the variable timezone to change the time1 and time2 values to its corresponding local times? that is:

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

Figured it out, it ain't that great but it's honest work:

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)

Output:

03:00

08:00

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM