怎么用脚本获取互联网时间

wen 实用脚本 2

本文目录导读:

怎么用脚本获取互联网时间

  1. Python(使用 requests + datetime
  2. JavaScript(Node.js)
  3. Bash(使用 curl + date
  4. PowerShell(Windows)
  5. Python 另一种简单方法(使用 HTTP 头)
  6. 常用免费时间 API
  7. 注意事项

Python(使用 requests + datetime

import requests
from datetime import datetime
def get_internet_time():
    try:
        # 使用 WorldTimeAPI(免费,无需密钥)
        response = requests.get('https://worldtimeapi.org/api/ip', timeout=5)
        data = response.json()
        # 解析 ISO 格式时间
        dt = datetime.fromisoformat(data['utc_datetime'].replace('Z', '+00:00'))
        return dt.astimezone()  # 转换为本地时区
    except Exception as e:
        print(f"获取失败: {e}")
        return None
# 使用示例
time = get_internet_time()
if time:
    print(f"互联网时间: {time.strftime('%Y-%m-%d %H:%M:%S %Z')}")

JavaScript(Node.js)

// 使用 fetch(Node.js 18+ 或浏览器)
async function getInternetTime() {
    try {
        const response = await fetch('https://worldtimeapi.org/api/ip');
        const data = await response.json();
        return new Date(data.utc_datetime);
    } catch (error) {
        console.error('获取失败:', error);
        return null;
    }
}
// 使用示例
getInternetTime().then(time => {
    if (time) console.log(`互联网时间: ${time.toLocaleString()}`);
});

Bash(使用 curl + date

# 简单方法:从 HTTP 响应头获取时间
curl -sI https://google.com | grep -i '^date:' | sed 's/^[Dd]ate: //'
# 更精确的方法(使用第三方 API)
curl -s https://worldtimeapi.org/api/ip | jq -r '.utc_datetime'

PowerShell(Windows)

# 方法1:使用 HTTP 头
$response = Invoke-WebRequest -Uri 'https://www.google.com' -Method Head
$internetTime = [DateTime]::Parse($response.Headers['Date'])
# 方法2:使用 API
$data = Invoke-RestMethod -Uri 'https://worldtimeapi.org/api/ip'
$internetTime = [DateTime]::Parse($data.utc_datetime)
Write-Host "互联网时间: $internetTime"

Python 另一种简单方法(使用 HTTP 头)

import requests
from email.utils import parsedate_to_datetime
def get_time_from_header():
    response = requests.head('https://www.baidu.com', timeout=5)
    date_str = response.headers['Date']
    return parsedate_to_datetime(date_str)
# 使用示例
time = get_time_from_header()
print(f"互联网时间: {time}")

常用免费时间 API

服务 地址 特点
WorldTimeAPI https://worldtimeapi.org/api/ip 根据 IP 自动判断时区
TimeAPI https://timeapi.io/api/Time/current/zone?timeZone=UTC 支持指定时区
百度 https://www.baidu.com(HTTP 头) 简单快速,无需额外依赖

注意事项

  1. 时区处理:建议先获取 UTC 时间,再根据业务需求转换时区。
  2. 错误处理:务必添加超时和异常处理,避免网络问题导致程序崩溃。
  3. 并发安全:如果多线程使用,注意时间同步问题。
  4. 备用方案:可以配置多个 API,避免单一服务不可用。

选择哪种方式取决于你的开发环境和用途,如果需要更精确的时间(毫秒级),建议使用 NTP 协议,但以上方法对大多数场景已经足够。

抱歉,评论功能暂时关闭!