简体   繁体   中英

How do I find the difference in hours between two time zones?

I have this code here that can find the time in two different timezones at the moment. I want to calculate the difference in hours, between the two timezones.

def time_caluclator(timezone1, timezone2):

    dt_utcnow = datetime.datetime.now(tz=pytz.UTC)

    dt_1 = dt_utcnow.astimezone(pytz.timezone(timezone1))
    dt_2 = dt_utcnow.astimezone(pytz.timezone(timezone2))

    print(dt_1, dt_2)

This is the code, and it will print this:

2022-05-15 00:44:22.031149+00:00 2022-05-15 01:44:22.031149+01:00

(First timezone is Zulu, and the other is WET).

I would do two nested for loops to separate your times into sections by both spaces and ":" so that you can get the individual numbers. Then its just subtraction and maybe a dictionary if you would like to say specifically timezone codes like "EST"

def time_caluclator(timezone1, timezone2):
    off1 = pytz.timezone(timezone1).utcoffset(datetime.datetime.now())
    off2 = pytz.timezone(timezone2).utcoffset(datetime.datetime.now())
    return (off2 - off1).seconds // 3600

Works correct for pytz timezones such as "US/Eastern", "Europe/Moscow".

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