0

Update: I found a solution to this question and posted it in the comment.

I'm new to Python. I've been searching for resources to guide me how to display local time in a different timezone (in UTC), but all I found was converting based on current time.

For example, my local timezone is 'Asia_Singapore'. How to I get the my local time in UTC - 1 which is 7:00 AM?

If it helps, I'm trying to do something like this tool: https://www.timeanddate.com/worldclock/meetingtime.html?iso=20230106&p1=145&p2=108&p3=56&p4=304&p5=179&p6=220

One of the code snippet I tried was from this page:

from datetime import datetime

import pytz

fmt = '%Y-%m-%d %H:%M:%S %Z%z'

# Print current time
print(datetime.now().strftime(fmt))

# Show current time in Berlin timezone
tz_berlin = pytz.timezone('Europe/Berlin')
local = tz_berlin.localize(datetime.now())
print("Berlin Time::", local.strftime(fmt))

# Show UTC + 2 time in local timezone
tz_sin = pytz.timezone('Asia/Singapore')
dt = datetime(2023, 1, 6, 2, 0, 0)
local = tz_sin.localize(dt)
print("Singapore Time in UTC + 2::", local.strftime(fmt))

Output:

2023-01-06 10:27:44 
Berlin Time:: 2023-01-06 10:27:44 CET+0100
Singapore Time in UTC + 2:: 2023-01-06 02:00:00 +08+0800

What I expected:

2023-01-06 18:27:44
Berlin Time:: 2023-01-06 11:27:44 CET+0100
Singapore Time in UTC + 2:: 2023-01-06 10:00:00 +08+0800

Thank you in advance!

FObersteiner
  • 22,500
  • 8
  • 42
  • 72
Bally
  • 41
  • 3
  • 12

1 Answers1

0

I think I found a solution without using any library. I just need to calculate the time difference between the local timezone and the targeted time in UTC.

Here's how I did it:

def convert_tz(tz, target_tz):

    new_tz = int(tz) + int(target_tz)

    print("New timezone: {}".format(new_tz))

    if new_tz < 12 and new_tz >= 0:
        return str(new_tz) + "AM"
    elif new_tz >= 12:
        return str(12 - new_tz) + " PM"
    else:
        return str(24+new_tz-12) + "PM"

target_tz = "-1"
print("Target timezone: {}".format(target_tz))
tz = ["8","-5","0","-7","+7","+2"]

for item in tz:
    print("Original timezone: {}".format(item))
    print("Converted time: {}".format(convert_tz(item, target_tz)))
Bally
  • 41
  • 3
  • 12