'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).



Solution 1:[1]

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"

Solution 2:[2]

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".

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Zach Frank
Solution 2 Max Smirnov