一、需求背景
為了獲取網絡時間,采用python實現。
二、代碼
# -*- coding: utf-8
import sys
import time
import requests
# 1、獲取網絡北京時間戳
def get_beijing_stamp_from_web(url):
# 請求網絡數據
response = requests.get(url)
# 獲取http頭date部分
ts = response.headers['date']
# 將日期時間字符轉化為數組對象
gmt_time_obj = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
# 將時間數組對象轉為時間戳
gmt_ts = time.mktime(gmt_time_obj) # 零時區時間戳
# 將GMT時間轉換成北京時間時間戳
bj_internet_ts = int(gmt_ts + 8 * 3600) # 北京時間戳
# 返回東八區的北京時間戳
return bj_internet_ts
# 2、獲取網絡北京日期字串
def get_beijing_date_from_web(url):
# 請求網絡數據
response = requests.get(url)
# 獲取http頭date部分
ts = response.headers['date']
# 將日期時間字符轉化為數組對象
gmt_time_obj = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S") # GMT零時區
# 將時間數組對象轉為時間戳
gmt_ts = time.mktime(gmt_time_obj) # 零時區時間戳
# 將GMT時間轉換成北京時間時間戳
bj_internet_ts = gmt_ts + 8 * 3600 # 北京時間戳
# 將北京時間戳轉化為數組對象
bj_local_time_obj = time.localtime(bj_internet_ts)
# 構造日期字串
str1 = "%u-%02u-%02u" % (bj_local_time_obj.tm_year,
bj_local_time_obj.tm_mon, bj_local_time_obj.tm_mday)
str2 = "%02u:%02u:%02u" % (
bj_local_time_obj.tm_hour, bj_local_time_obj.tm_min, bj_local_time_obj.tm_sec)
bj_date_time_str = "%s %s" % (str1, str2) # 日期字串
# 返回東八區的北京時間戳
return bj_date_time_str
# 3、獲取網絡GMT時間戳
def get_gmt_stamp_from_web(url):
# 請求網絡數據
response = requests.get(url)
# 獲取http頭date部分
ts = response.headers['date']
# 將web日期時間字符轉化為數組對象
gmt_time = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
# 將數組對象時間轉換成時間戳
gmt_internet_ts = int(time.mktime(gmt_time)) # 零時區時間戳
# 返回零時區時間戳
return gmt_internet_ts
# 4、獲取網絡GMT日期字串
def get_gmt_date_from_web(url):
# 請求網絡數據
response = requests.get(url)
# 獲取http頭date部分
ts = response.headers['date']
# 將web日期時間字符轉化為數組對象
gmt_time_boj = time.strptime(ts[5:25], "%d %b %Y %H:%M:%S")
# 構建時間字符串
str1 = "%u-%02u-%02u" % (gmt_time_boj.tm_year,
gmt_time_boj.tm_mon, gmt_time_boj.tm_mday)
str2 = "%02u:%02u:%02u" % (
gmt_time_boj.tm_hour, gmt_time_boj.tm_min, gmt_time_boj.tm_sec)
gmt_date_time = "%s %s" % (str1, str2)
# 返回零時區日期字串
return gmt_date_time
def main():
url = 'http://www.baidu.com'
x = get_beijing_stamp_from_web(url)
print("北京時間戳:")
print(x)
x = get_beijing_date_from_web(url)
print("北京日期串:")
print(x)
x = get_gmt_stamp_from_web(url)
print("GMT時間戳:")
print(x)
x = get_gmt_date_from_web(url)
print("GMT日期串:")
print(x)
if __name__ == '__main__':
main()
輸出:
北京時間戳:
1619589692
北京日期串:
2021-04-28 14:01:32
GMT時間戳:
1619560892
GMT日期串:
2021-04-28 06:01:32
