You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python实现API响应中UTC转CST及datetime字段提取问题

问题描述

我用Python从API获取天气数据,想要把响应中datetime字段的UTC时间转换为CST时间并展示,但无法正确提取该字段。

我的代码

import requests
import json

weather = requests.get('...')
j = json.loads(weather.text)
print (json.dumps(j, indent=2))

API响应结果

{
  "metadata": null,
  "data": [
    {
      "datetime": "2022-12-11T05:00:00Z",
      "is_day_time": false,
      "icon_code": 5,
      "weather_text": "Clear with few low clouds and few cirrus",
      "temperature": {
        "value": 45.968,
        "units": "F"
      },
      "feels_like_temperature": {
        "value": 39.092,
        "units": "F"
      },
      "relative_humidity": 56,
      "precipitation": {
        "precipitation_probability": 4,
        "total_precipitation": {
          "value": 0.0,
          "units": "in"
        }
      },
      "wind": {
        "speed": {
          "value": 5.144953471725125,
          "units": "mi/h"
        },
        "direction": 25
      },
      "wind_gust": {
        "value": 9.014853256979242,
        "units": "mi/h"
      },
      "pressure": {
        "value": 29.4171829577118,
        "units": "inHg"
      },
      "visibility": {
        "value": 6.835083114610673,
        "units": "mi"
      },
      "dew_point": {
        "value": 31.01,
        "units": "F"
      },
      "cloud_cover": 31
    },
    {
      "datetime": "2022-12-11T06:00:00Z",
      "is_day_time": false,
      "icon_code": 4,
      "weather_text": "Clear with few low clouds",
      "temperature": {
        "value": 45.068,
        "units": "F"
      },
      "feels_like_temperature": {
        "value": 38.066,
        "units": "F"
      },
      "relative_humidity": 56,
      "precipitation": {
        "precipitation_probability": 5,
        "total_precipitation": {
          "value": 0.0,
          "units": "in"
        }
      },
      "wind": {
        "speed": {
          "value": 5.167322834645669,
          "units": "mi/h"
        },
        "direction": 27
      },
      "wind_gust": {
        "value": 8.724051539012168,
        "units": "mi/h"
      },
      "pressure": {
        "value": 29.4213171559632,
        "units": "inHg"
      },
      "visibility": {
        "value": 5.592340730136005,
        "units": "mi"
      },
      "dew_point": {
        "value": 30.2,
        "units": "F"
      },
      "cloud_cover": 13
    },
    {
      "datetime": "2022-12-11T07:00:00Z",
      "is_day_time": false,
      "icon_code": 4,
      "weather_text": "Clear with few low clouds",
      "temperature": {
        "value": 44.33,
        "units": "F"
      },
      "feels_like_temperature": {
        "value": 37.364,
        "units": "F"
      },
      "relative_humidity": 56,
      "precipitation": {
        "precipitation_probability": 4,
        "total_precipitation": {
          "value": 0.0,
          "units": "in"
        }
      },
      "wind": {
        "speed": {
          "value": 4.988367931281317,
          "units": "mi/h"
        },
        "direction": 28
      },
      "wind_gust": {
        "value": 8.254294917680744,
        "units": "mi/h"
      },
      "pressure": {
        "value": 29.4165923579616,
        "units": "inHg"
      },
      "visibility": {
        "value": 7.456454306848007,
        "units": "mi"
      },
      "dew_point": {
        "value": 29.714,
        "units": "F"
      },
      "cloud_cover": 22
    }
  ],
  "error": null
}
解决方案

1. 正确提取datetime字段

响应里的datetime嵌套在data数组的每个对象中,直接遍历j['data']就能逐个获取:

for item in j['data']:
    utc_time_str = item['datetime']
    print(utc_time_str)

2. UTC转CST时间

根据Python版本选择下面两种方法之一:

方法一:用内置zoneinfo(Python 3.9+)

import requests
import json
from datetime import datetime
from zoneinfo import ZoneInfo

weather = requests.get('...')
j = json.loads(weather.text)

for item in j['data']:
    # 解析UTC时间字符串
    utc_dt = datetime.fromisoformat(item['datetime'].replace('Z', '+00:00'))
    # 转换为中国标准时间(CST,UTC+8)
    cst_dt = utc_dt.astimezone(ZoneInfo('Asia/Shanghai'))
    # 格式化输出
    print(f"UTC时间: {utc_dt.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"CST时间: {cst_dt.strftime('%Y-%m-%d %H:%M:%S')}")
    print("---")

方法二:用pytz(兼容旧版Python)

先安装依赖:

pip install pytz

再编写代码:

import requests
import json
from datetime import datetime
import pytz

weather = requests.get('...')
j = json.loads(weather.text)

utc_zone = pytz.utc
cst_zone = pytz.timezone('Asia/Shanghai')

for item in j['data']:
    # 解析UTC时间
    utc_dt = datetime.strptime(item['datetime'], '%Y-%m-%dT%H:%M:%SZ')
    utc_dt = utc_zone.localize(utc_dt)
    # 转换为CST
    cst_dt = utc_dt.astimezone(cst_zone)
    # 格式化输出
    print(f"UTC时间: {utc_dt.strftime('%Y-%m-%d %H:%M:%S')}")
    print(f"CST时间: {cst_dt.strftime('%Y-%m-%d %H:%M:%S')}")
    print("---")

说明

  • 上述代码中的Asia/Shanghai对应中国标准时间(UTC+8),如果需要的是美国中部时间(CST,UTC-6/UTC-5),替换为America/Chicago即可。

内容的提问来源于stack exchange,提问作者uncrayon

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 14:40:37