萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

Python 獲取標準北京時間:HTTP API 解析 beijing-time.org

接口分析

https://www.beijing-time.org/time.asp 返回純文本 key=value 格式:

nyear=2024
nmonth=3
nday=15
nhrs=14
nmin=30
nsec=45
nwday=5

解析代碼(兼容 Py2/3)

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

生產環境建議

  • 增加緩存(如 1 分鐘內不重複請求)
  • 備選源:https://api.m.taobao.com/rest/api3.do?api=mtop.common.getTimestamp(毫秒級時間戳)
  • 異常重試與指數退避
  • 若有系統權限,優先配置 chrony/systemd-timesyncd 走 NTP
copyright © 萬盛學電腦網 all rights reserved