使用 ntp 时间时,(英国)返回的时间总是比实际时间少一小时。例如:现在时间是 13.35 但当我说日期时,它返回 12.35。有什么建议 ?
try:
c = ntplib.NTPClient()
response = c.request('uk.pool.ntp.org', version=3)
except:
print "Error At Time Sync: Let Me Check!"
最佳答案
最后,我可以找出答案,如果有人正在寻找答案,UTC 时间与英国夏令时 (BST) 不同 [必须相应地 + 或 - 一些小时] 在 python 中,有一个名为的库pytz该库允许使用 Python 2.4 或更高版本进行准确的跨平台时区计算。这是我的编码的样子。希望这会对某人有所帮助。谢谢!!
#!/usr/bin
import pytz
import datetime
import ntplib
import time
LOCALTIMEZONE = pytz.timezone("Europe/London") # time zone name from Olson database
def utc_to_local(utc_dt):
return utc_dt.replace(tzinfo=pytz.utc).astimezone(LOCALTIMEZONE)
def get_time_from_NTPClient():
from time import ctime
try:
c = ntplib.NTPClient()
response = c.request('europe.pool.ntp.org', version=3)
formatted_date_with_micro_seconds = datetime.datetime.strptime(str(datetime.datetime.utcfromtimestamp(response.tx_time)),"%Y-%m-%d %H:%M:%S.%f")
local_dt = utc_to_local(formatted_date_with_micro_seconds)
#Remove micro seconds from the string
formatted_date_with_corrections = str(local_dt).split(".")[0]
return formatted_date_with_corrections
except:
print "Error At Time Sync: Let Me Check!"
return "Error At Time Sync: Let Me Check!"
formatted_date = get_time_from_NTPClient()
关于python - NTPLib 时差 + Python,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29561751/