Sunrise-Sunset API传入经纬度参数返回异常结果求助
问题原因与解决方案:sunrise-sunset.org API返回异常时间
问题根源
sunrise-sunset.org API默认返回UTC标准时间,你提供的经纬度对应巴基斯坦伊斯兰堡附近,当地时区是UTC+5。你看到的“异常时间”其实是未转换的UTC时间——比如返回的12:56:37 AM UTC,加上5小时后就是当地正常的5:56:37 AM日出时间。
解决方案
有两种简单处理方式:
方式1:手动转换UTC时间为当地时区
直接对API返回的UTC时间做时区偏移计算:
import requests from datetime import datetime, timedelta LAT = 33.648953 LNG = 73.177007 params = { "lat": LAT, "lng": LNG } response = requests.get("https://api.sunrise-sunset.org/json", params=params) response.raise_for_status() data = response.json() # UTC转巴基斯坦当地时间(UTC+5) def utc_to_pakistan(utc_time_str): utc_dt = datetime.strptime(utc_time_str, "%I:%M:%S %p") local_dt = utc_dt + timedelta(hours=5) return local_dt.strftime("%I:%M:%S %p") # 转换所有时间字段(跳过day_length,因为它是时长) local_results = { key: utc_to_pakistan(value) if key != "day_length" else value for key, value in data["results"].items() } print("巴基斯坦当地时间结果:", local_results)
方式2:调用API时直接指定时区
API支持通过tz参数指定时区,直接返回当地时间:
import requests LAT = 33.648953 LNG = 73.177007 params = { "lat": LAT, "lng": LNG, "tz": "Asia/Karachi" # 巴基斯坦时区标识符 } response = requests.get("https://api.sunrise-sunset.org/json", params=params) response.raise_for_status() data = response.json() print("API直接返回的当地时间:", data["results"])
也可以用formatted=0参数获取ISO 8601格式时间戳,再自行解析转换:
import requests from datetime import datetime params = { "lat": 33.648953, "lng": 73.177007, "formatted": 0 } response = requests.get("https://api.sunrise-sunset.org/json", params=params) data = response.json() # 解析UTC时间戳并转换为巴基斯坦时区 sunrise_utc = datetime.fromisoformat(data["results"]["sunrise"].replace("Z", "+00:00")) local_sunrise = sunrise_utc.astimezone() # 自动适配本地时区,或指定时区如datetime.timezone(timedelta(hours=5)) print("当地日出时间:", local_sunrise.strftime("%I:%M:%S %p"))
验证说明
手动计算验证:返回的UTC日出时间12:56:37 AM + 5小时 = 5:56:37 AM,这完全符合伊斯兰堡地区的实际日出时间范围,说明API返回的数据本身是正确的,只是默认输出UTC时区的时间。
内容的提问来源于stack exchange,提问作者Muhammad Shamshad Aslam
相关产品推荐
相关产品推荐

