赞
踩
通常获取网络时间是从ntp服务器获取,但是对时间要求精度不高的话,还有更加简便的方法,直接透过http访问http://time1909.beijing-time.org/time.asp
t0=new Date().getTime();
nyear=2021;
nmonth=4;
nday=25;
nwday=7;
nhrs=16;
nmin=46;
nsec=24;
用Python request模块访问http://time1909.beijing-time.org/time.asp,抓取返回数据即可
# -*- coding: utf-8 -*- import os import time import requests def getNetTime(): try: head = {'User-Agent': 'Mozilla/5.0'} url = r'http://time1909.beijing-time.org/time.asp' # requests get r = requests.get(url=url,headers=head) # 检查返回码 if r.status_code == 200: # 得到返回报文信息 result = r.text print('r.text:',r.text) # 通过;分割文本; data = result.split(";") # print('data:',data) # ====================================================== # 以下是数据文本处理:切割; year = data[1].split('=')[1] # year=2021 month = data[2].split('=')[1] day = data[3].split('=')[1] # wday = data[4].split('=')[1] hrs = data[5].split('=')[1] minute = data[6].split('=')[1] sec = data[7].split('=')[1] # ====================================================== timestr = "%s/%s/%s %s:%s:%s" % (year, month, day, hrs, minute, sec) print(timestr) # 将timestr转为时间戳格式; timestrp = time.mktime(time.strptime(timestr, "%Y/%m/%d %X")) #返回时间戳; return (timestrp,timestr) except: return (-1) if __name__ == '__main__': print('timer:',getNetTime())
D:\work\demo>time.py
r.text: t0=new Date().getTime();
nyear=2021;
nmonth=4;
nday=25;
nwday=7;
nhrs=16;
nmin=44;
nsec=41;
2021/4/25 16:44:41
timer: (1619340281.0, '2021/4/25 16:44:41')
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。