在我们进行注册码的有效期验证时,通常使用获取网络时间的方式来进行比对。
以下为获取网络时间的几种方式。
一、获取网络时间,需要的时间会比较长,个别电脑上可能会出现不兼容现象
代码实现:
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