更新:我找到了这个问题的解决方案,并将其发布在评论中。
我是Python的新手。我一直在寻找资源来指导我如何在不同的时区(在UTC)显示本地时间,但我发现的都是基于当前时间的转换。
例如,我的本地时区是'Asia_Singapore'。我如何得到我的当地时间在UTC - 1,这是上午7点?
如果它有帮助,我正在尝试做这样的工具:https://www.timeanddate.com/worldclock/meetingtime.html?iso=20230106&p1=145&p2=108&p3=56&p4=304&p5=179&p6=220
我试过的一个代码片段来自这个页面:
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))
输出:
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
我所期望的:
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
提前感谢!
我想我找到了一个不使用任何库的解决方案。我只需要计算本地时区和UTC目标时间之间的时间差。
我是这样做的:
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)))