日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Python獲取網絡時間戳的兩種方法詳解_python

作者:幸福的達哥 ? 更新時間: 2022-03-28 編程語言

在我們進行注冊碼的有效期驗證時,通常使用獲取網絡時間的方式來進行比對。

以下為獲取網絡時間的幾種方式。

方法一

需要的時間會比較長,個別電腦上可能會出現不兼容現象

代碼實現

 def get_web_server_time(self, host_URL, year_str='-', time_str=':'):
        '''
        獲取網絡時間,需要的時間會比較長,個別電腦上可能會出現不兼容現象
        :param host_URL: 目標網址,如:https://www.baidu.com/
        :param year_str: 年份中間的間隔字符,如:2019-11-22
        :param time_str: 小時和分鐘中將的間隔字符,如:12:30:59
        :return: 返回時間字符串,如:2019-11-22 12:30:59
        '''
        conn = http.client.HTTPConnection(host_URL)
        conn.request("GET", "/")
        r = conn.getresponse()
        # r.getheaders() #獲取所有的http頭
        ts = r.getheader('date')  # 獲取http頭date部分
        print(ts)
        # 將GMT時間轉換成北京時間
        ltime = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
        print(ltime)
        ttime = time.localtime(time.mktime(ltime) + 8 * 60 * 60)
        print(ttime)
        year_out = "{}{}{:0>2}{}{:0>2}".format(ttime.tm_year, year_str, ttime.tm_mon, year_str, ttime.tm_mday)
        time_out = "{:0>2}{}{:0>2}{}{:0>2}".format(ttime.tm_hour, time_str, ttime.tm_min, time_str, ttime.tm_sec)
 
        output_str = year_out + "" + time_out
        print("目標網址={} 的網絡時間={}".format(host_URL, output_str))
 
        print("return 時間={}".format(output_str))
        return output_str

調用方法

if __name__ == '__main__':
    test=Admin()
    test.get_web_server_time('www.baidu.com')

返回結果

目標網址=www.baidu.com 的網絡時間=2022-01-11 19:58:02
return 時間=2022-01-11 19:58:02

方法二

獲取網絡時間,返回時間格式為毫秒:2019-12-13 11:39:48.398

代碼實現

def get_web_now_time(self, time_format='YYYY-MM-DD HH:mm:ss.SSS'):
        """
        獲取網絡時間,返回時間格式:2019-12-13 11:39:48.398
        :param time_format:控制返回字符串的格式,默認為:'YYYY-MM-DD HH:mm:ss.SSS'
        :return: 
        """
        import arrow as ar
        import requests as req
        print('\n=========    獲取網絡時間   =========')
 
        try:
            res = req.get('https://www.baidu.com/').headers['Date']
            # res = req.get('https://www.hao123.com/').headers['Date']
            time_diff = ar.get(res[4:-4], 'DD MMM YYYY HH:mm:ss') - ar.now().floor('second')
            web_now_time = (ar.now() + time_diff).format(time_format)
 
            print('web_now_time={}'.format(web_now_time))
 
            return web_now_time
        except BaseException as e:
            print('獲取網絡時間出錯,出錯原因:{}'.format(e))
            return -1

調用方法

if __name__ == '__main__':
    test=Admin()
    test.get_web_now_time()

返回結果

========= ? ?獲取網絡時間 ? =========
web_now_time=2022-01-11 22:37:30.360

原文鏈接:https://blog.csdn.net/zh6526157/article/details/122424784

欄目分類
最近更新