在python中获取正确时间的简便方法

时间:2011-03-07 17:28:27

标签: python datetime

我正在群集上运行一些作业,其中每个节点上的日期彼此稍微偏离。有没有一种简单的方法可以通过python从互联网上的某个地方获取时间,还是我需要让sysadmin更频繁地同步机器之间的时间?

我想在我发布的每个作业的输出中加上时间戳,但显然python的time.strftime()等的准确性将取决于机器知道正确的时间。我会在几秒钟内感受到准确性,但现在它只需几分钟。

5 个答案:

答案 0 :(得分:8)

我正在处理运行Linux 2.6.33,Python 2.6.5的独立传感器设备,遗憾的是缺少实时时钟,但 具有网络功能。此外,该设备使用BusyBox,因此它具有最小化的工具功能集。

我创建了以下脚本,该脚本在网络运行后执行以更正系统时间。我的解决方案可能并不完全解决原始问题(听起来诺亚是用户而不是系统管理员),但这个问题是在使用Python通过NTP搜索同步系统时钟时出现的问题。我认为它可能会帮助其他人降落在这里。

在使用脚本之前,您需要安装ntplib。下载链接和安装说明位于:https://pypi.python.org/pypi/ntplib/

将下面代码的内容复制到一个文件(我名为“synctime.py”)。然后,在网络运行后,执行脚本(例如“python synctime.py”)。您需要使用提升(root)权限才能正常工作。

import time
import os

try:
    import ntplib
    client = ntplib.NTPClient()
    response = client.request('pool.ntp.org')
    os.system('date ' + time.strftime('%m%d%H%M%Y.%S',time.localtime(response.tx_time)))
except:
    print('Could not sync with time server.')

print('Done.')

答案 1 :(得分:5)

听起来你应该考虑使用类似NTP的东西来保持机器的时间彼此同步(最好是全球标准的时间源)。

答案 2 :(得分:4)

尝试使用ntplib for python。我玩了一下它看起来很稳定。

https://pypi.python.org/pypi/ntplib/

答案 3 :(得分:0)

在cmd上运行“ w32tm / resync”。

import os

os.system('w32tm /resync')

答案 4 :(得分:0)

-->在 cmd 上运行“w32tm /resync”。

这对我来说不起作用。

对我有用:

        client = ntplib.NTPClient()
        response = client.request('pool.ntp.org')
        t = datetime.fromtimestamp(response.tx_time)
        time_ntp = t.strftime("%m %d %H:%M:%S %Y")#Mon Jul 05 13:58:39 2021
        print('NTP Time='+str(time_ntp))
        #os.system('w32tm /resync')
        os.system('date ' +  t.strftime("%x"))
        os.system('time ' +  t.strftime("%X"))

-praveen