获取指定时区的日期时间,而不管计算机中设置的日期时间如何

Get datetime of specified timezone irrespective of datetime set in computer

我想打印时区 "Asia/Kathmandu" 的日期时间。我使用了以下代码:

import datetime, pytz

tz = pytz.timezone("Asia/Kathmandu")
ktm_now = datetime.datetime.now(tz)
print(ktm_now)

问题是它给了我计算机中设置的日期时间,而不是 "Asia/Kathmandu" 的日期时间。现在 "Asia/Kathmandu" 的日期时间应该是 19:55:00 但我已经手动将计算机的时间更改为 21:30:00。这样做之后,一旦我 运行 上面的代码,它就会令人惊讶地给我计算机的日期时间 (21:30:00) 而不是 19:55:00。可能是什么原因?如何获取指定时区的日期时间 "Asia/Kathmandu" 而不是计算机中设置的日期时间?

这是一种从独立来源获取时间的方法(假设您可以访问互联网):

import datetime
import ntplib # pip install ntplib
import dateutil # Python 3.9: use zoneinfo

tz_info = dateutil.tz.gettz("Asia/Kathmandu")

ntp_server = 'pool.ntp.org'
c = ntplib.NTPClient()

response = c.request(ntp_server)
dt = datetime.datetime.fromtimestamp(response.tx_time, tz=tz_info)
# response.tx_time holds NTP server timestamp in seconds since the epoch / Unix time
# note that using response.tx_time here ignores network delay

print(dt)
# 2021-03-06 21:13:20.112861+05:45

print(repr(dt))
# datetime.datetime(2021, 3, 6, 21, 13, 20, 112861, tzinfo=tzfile('/usr/share/zoneinfo/Asia/Kathmandu'))

print(dt.utcoffset())
# 5:45:00

包:ntplib, background info: Network Time Protocol