如何将 API UTC 时间转换为本地时间 (+13:00)

How do I convert an API UTC time to local time (+13:00)

我正在尝试从将日期时间值存储为 UTC 的 API 转换日期时间。我需要将日期时间转换为本地时间 'Pacific/Auckland'

我用的API是Sunrise-Sunsethttps://sunrise-sunset.org/api

我要求的具体地点是新西兰基督城https://sunrise-sunset.org/search?location=christchurch

import requests

api_url = 'https://api.sunrise-sunset.org/json?lat=-43.525650&lng=172.639847&formatted=0'
response = requests.get(api_url)

if response.status_code == 200:
    sunset_today = response.json()['results']['sunset']
    print(sunset_today) # outputs '2021-09-26T06:31:41+00:00'

我广泛搜索了 Whosebug 和 Google,但似乎找不到适合我需要的解决方案。

我问的问题是

  1. 如何将 UTC 值转换为本地日期时间 ('Pacific/Auckland')?

仅供参考,我不想让应用程序变得臃肿,但是从以前(不成功的)解决这个问题的尝试来看,我已经安装了 tzlocalpytz 包。

我正在 Django 3.2.7 中编写我的应用程序并调整了我的 settings.py TIME_ZONE = 'Pacific/Auckland'

编辑 尝试将字符串转换为 datetime 时出现以下错误。 时间数据“2021-09-26T06:31:41+00:00”与格式“%Y-%m-%dT%H:%M:%S %Z”不匹配

sunset_today = response.json()['results']['sunset']
format = '%Y-%m-%dT%H:%M:%S %Z'
parsed_date = datetime.strptime(sunset_today, format)
print(parsed_date) 

# ERROR: time data '2021-09-26T06:31:41+00:00' does not match format '%Y-%m-%dT%H:%M:%S %Z'*

将时区感知字符串转换为 python 日期时间更易于使用 fromisoformat,因为无论如何您都是从 API 获取 ISO 格式的字符串:

import datetime

sunset_today = response.json()['results']['sunset']
parsed_date = datetime.datetime.fromisoformat(sunset_today)
# 2021-09-26 06:31:41+00:00

我使用 dateutilpytz 库解决了这个问题

import requests
import pytz
from dateutil import parser

api_url = 'https://api.sunrise-sunset.org/json?lat=-43.525650&lng=172.639847&formatted=0'
response = requests.get(api_url)

nz_zone = pytz.timezone('Pacific/Auckland')
        
if response.status_code == 200:
    sunset_today = response.json()['results']['sunset']
    converted_date = parser.parse(sunset_today).astimezone(nz_zone)
    print(converted_date) # outputs 2021-09-26 19:31:41+13:00