python3.7 获取网络时间
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                python3.7 获取网络时间
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                1,從網頁獲取時間 網址: https://beijing-time.org/
 在頭信息中有個GMT時間 稍加轉換就是北京時間了
 
 獲取時間的代碼如下
另外也可以從 https://www.beijing-time.org/t/time.asp 獲取時間
 
 返回值: t0=new Date().getTime(); nyear=2022; nmonth=1; nday=10; nwday=1; nhrs=10; nmin=48; nsec=59;
 剩下的就是字符串的截取拼裝
2 利用ntp同步時間
 網絡時間協議,英文名稱:Network Time Protocol(NTP)是用來使計算機時間同步化的一種協議,它可以使計算機對其服務器或時鐘源(如石英鐘,GPS等等)做同步化,它可以提供高精準度的時間校正(LAN上與標準間差小于1毫秒,WAN上幾十毫秒),且可介由加密確認的方式來防止惡毒的協議攻擊。NTP的目的是在無序的Internet環境中提供精確和健壯的時間服務。
 關于時間網絡協議的相關內容百度一下: 網絡時間協議
前提:
 1 ntp服務器 https://dns.icoa.cn/ntp/
 2 下載 ntp庫 pip install ntplib
 代碼如下
兩種獲取時間的完整代碼如下
# -*- coding: utf-8 -*- import datetime import timeimport ntplib import requestsdef get_beijin_time():try:url = 'https://beijing-time.org/'request_result = requests.get(url=url)if request_result.status_code == 200:headers = request_result.headersnet_date = headers.get("date")gmt_time = time.strptime(net_date[5:25], "%d %b %Y %H:%M:%S")bj_timestamp = int(time.mktime(gmt_time) + 8 * 60 * 60)return datetime.datetime.fromtimestamp(bj_timestamp)except Exception as exc:return datetime.datetime.now()def get_ntp_time():ntp_client = ntplib.NTPClient()response = ntp_client.request('cn.ntp.org.cn')return datetime.datetime.fromtimestamp(response.tx_time)if __name__ == '__main__':bj_time = get_beijin_time()print("北京時間: ", bj_time)ntp_time = get_ntp_time()print("ntp時間: ", ntp_time)總結
以上是生活随笔為你收集整理的python3.7 获取网络时间的全部內容,希望文章能夠幫你解決所遇到的問題。
                            
                        - 上一篇: SQLserver 2005 安装文档
 - 下一篇: 前端学习(1362):学生档案信息管理4