Python檢查和同步本地時間(北京時間)的實現(xiàn)方法
背景
有時本地服務器的時間不準了,需要同步互聯(lián)網(wǎng)上的時間。
解決方案
- NTP時間同步,找到一些可用的NTP服務器進行同步即可。
- 通過獲取一些大型網(wǎng)站的時間來同步為自己的時間。
* 由于NTP時間同步,如果相差比如有好幾個小時,那么時間不同步矯正回來其實是非常慢的;我本次主要就是講第2種方案,通過Python來實現(xiàn)的,可以直接設(shè)置為互聯(lián)網(wǎng)上的時間。
要點描述
- 假設(shè):百度、淘寶等非常大型的網(wǎng)站的時間是正確的
- 訪問百度、淘寶等網(wǎng)站,它返回的HTTP Header中包含一個時間戳(一般是GMT時間)。
- 根據(jù)這個時間戳,可以解析為當前的北京時間
- 可以檢查本地服務器時間與互聯(lián)網(wǎng)時間是否一致
- 可以使用date -s命令設(shè)置本地系統(tǒng)時間
- 還可以使用hwclock -w將系統(tǒng)時間同步回硬件中保存
代碼實現(xiàn)
代碼見:https://github.com/smilejay/python/blob/master/py2018/set_check_localtime.py
代碼在CentOS 7.4系統(tǒng)上Python 2.7上正常運行
為了考慮到兼容性和運行的方便性,代碼中發(fā)送HTTP請求沒有使用最流行的requests庫而是使用了urllib2這個Python標準庫。
# -*- coding: utf-8 import sys import time import subprocess import argparse import urllib2 def set_beijing_time_from_web(url): ''' set os and hardware clock as beijing time from internet ''' # use urllib2 in python2; not use requests which need installation response = urllib2.urlopen(url) #print response.read() # 獲取http頭date部分 ts = response.headers['date'] # 將日期時間字符轉(zhuǎn)化為time gmt_time = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S") # 將GMT時間轉(zhuǎn)換成北京時間 local_time = time.localtime(time.mktime(gmt_time) + 8*3600) str1 = "%u-%02u-%02u" % (local_time.tm_year, local_time.tm_mon, local_time.tm_mday) str2 = "%02u:%02u:%02u" % ( local_time.tm_hour, local_time.tm_min, local_time.tm_sec) cmd = 'date -s "%s %s"' % (str1, str2) #print cmd subprocess.check_call(cmd, shell=True) hw_cmd = 'hwclock -w' #print hw_cmd subprocess.check_call(hw_cmd, shell=True) print 'OK. set time: %s' % ' '.join([str1, str2]) def check_localtime_with_internet(url): ''' check local time with internet ''' threshold = 2 # use urllib2 in python2; not use requests which need installation response = urllib2.urlopen(url) #print response.read() # 獲取http頭date部分 ts = response.headers['date'] # 將日期時間字符轉(zhuǎn)化為time gmt_time = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S") # 將GMT時間轉(zhuǎn)換成北京時間 internet_ts = time.mktime(gmt_time) local_ts = time.mktime(time.gmtime()) if abs(local_ts - internet_ts) <= threshold: print 'OK. check localtime.' else: print 'ERROR! local_ts: %s internet_ts:%s' % (local_ts, internet_ts) sys.exit(1) if __name__ == '__main__': url = 'http://www.baidu.com' parser = argparse.ArgumentParser() parser.description = 'set/check localtime (i.e. CST) with internet' parser.add_argument('-c', '--check', action='store_true', help='only check local time') parser.add_argument('-s', '--set', action='store_true', help='only set local time') parser.add_argument('-u', '--url', default=url, help='the url to sync time') args = parser.parse_args() if args.set: set_beijing_time_from_web(args.url) else: check_localtime_with_internet(args.url)
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
基于python獲取本地時間并轉(zhuǎn)換時間戳和日期格式
這篇文章主要介紹了基于python獲取本地時間并轉(zhuǎn)換時間戳和日期格式,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下2020-10-10