Home > Software design >  How do i find the difference in hours between two timezones?
How do i find the difference in hours between two timezones?

Time:05-15

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

CodePudding user response:

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"

CodePudding user response:

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

  • Related