https://www.beijing-time.org/time.asp 返回純文本 key=value 格式:
nyear=2024 nmonth=3 nday=15 nhrs=14 nmin=30 nsec=45 nwday=5
import sys
import time
try:
import http.client as httplib # Py3
except ImportError:
import httplib # Py2
def get_beijing_time():
try:
conn = httplib.HTTPConnection("www.beijing-time.org", timeout=10)
conn.request("GET", "/time.asp")
resp = conn.getresponse()
if resp.status != 200:
return None
content = resp.read()
if isinstance(content, bytes):
content = content.decode('utf-8', errors='ignore')
data = {}
for line in content.split('\r\n'):
if '=' in line:
k, v = line.split('=', 1)
data[k.strip()] = v.strip()
dt_str = f"{data['nyear']}/{data['nmonth']}/{data['nday']} {data['nhrs']}:{data['nmin']}:{data['nsec']}"
return time.strptime(dt_str, "%Y/%m/%d %H:%M:%S")
except Exception as e:
print(f"Error: {e}")
return None
if __name__ == '__main__':
bt = get_beijing_time()
if bt:
print(time.strftime("%Y-%m-%d %H:%M:%S", bt))
else:
print("Failed to fetch")
time.struct_time 對象,可直接用 time.strftime 格式化,或轉 datetime:
from datetime import datetime dt = datetime(*bt[:6]) # year, month, day, hour, min, sec
https://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp(毫秒級時間戳)chrony/systemd-timesyncd 走 NTP