日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

python3.7 获取网络时间

發布時間:2023/12/10 python 24 豆豆
生活随笔 收集整理的這篇文章主要介紹了 python3.7 获取网络时间 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1,從網頁獲取時間 網址: https://beijing-time.org/
在頭信息中有個GMT時間 稍加轉換就是北京時間了

獲取時間的代碼如下

def 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()

另外也可以從 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
代碼如下

def get_ntp_time():ntp_client = ntplib.NTPClient()response = ntp_client.request('cn.ntp.org.cn')return datetime.datetime.fromtimestamp(response.tx_time)

兩種獲取時間的完整代碼如下

# -*- 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 获取网络时间的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。