问题描述
我要打印时区亚洲/加德满都"
的日期时间.我使用了以下代码:
I want to print the datetime of timezone "Asia/Kathmandu"
. I have used the below code:
import datetime, pytz
tz = pytz.timezone("Asia/Kathmandu")
ktm_now = datetime.datetime.now(tz)
print(ktm_now)
问题在于,它给了我在计算机中设置的日期时间,而不是亚洲/加德满都"
的日期时间.现在,亚洲/加德满都"
的日期时间应为 19:55:00
,但我已将计算机的时间手动更改为 21:30:00
.然后,执行上述代码后,它出人意料地给了我计算机的日期时间( 21:30:00
)而不是 19:55:00 代码>.可能是什么原因?如何获取指定时区(如
亚洲/加德满都"
)的日期时间,而不是计算机中设置的日期时间?
The problem is that it gave me the datetime that is set in my computer instead of datetime of "Asia/Kathmandu"
. Right now the datetime of "Asia/Kathmandu"
should be 19:55:00
but I have manually changed the time of my computer to 21:30:00
. And after doing this, as soon as I run the above code, it surprisingly gives me datetime which is of my computer (21:30:00
) instead of 19:55:00
. What can be the reason? How to get the datetime of a specified timezone like "Asia/Kathmandu"
instead of datetime set in computer?
推荐答案
以下是一种从独立来源获取时间的方法(假设您可以访问互联网):
Here's a way how to get the time from an independent source (assuming you have internet access):
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
package: ntplib, background info: Network Time Protocol
这篇关于不管计算机中设置的日期时间如何,都获取指定时区的日期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!