0

I want to convert a time(10AM) which is in EST to Asia(Dubai) timezone using UTC as my base time. I am to first convert the time (10AM) to UTC and then to Asia(Dubai) time.

1 Answers1

0

Try this:

from datetime import datetime, timezone, timedelta

def utc_to_tz(utc_dt, hours):
    return utc_dt.replace(tzinfo=timezone.utc).astimezone(tz=timezone(timedelta(hours=hours)))
def tz_to_utc(dt, tz_hours):
    return dt.replace(tzinfo=timezone(timedelta(hours=tz_hours))).astimezone(tz=timezone.utc)

x = datetime(2022, 7, 20, 14).astimezone(tz=timezone(timedelta(hours=-4))) # EST
print(x)

y = tz_to_utc(x, -4) # UTC
print(y)

z = utc_to_tz(y, +4) # Dubai
print(z)

Output:

2022-07-20 10:00:00-04:00
2022-07-20 14:00:00+00:00
2022-07-20 18:00:00+04:00
The Thonnu
  • 3,578
  • 2
  • 8
  • 30
  • Let me explain more. A student has a class by 10 AM which is in EST. He wants to know the time for his class by converting the 10 AM EST time to his local time zone assuming the student is staying in Dubai. But he has to first convert the 10 AM EST time to UTC (base time) before converting to his local time (Dubai) – Mary Chianumba Jul 20 '22 at 10:49
  • The outputs of the program are as follows: first line is EST; second line is UTC; third line is Dubai time. The output you want is the last line (18:00:00) – The Thonnu Jul 20 '22 at 11:31