python - 如何按时区获取时间,这会在 OpenWatherMap API 响应中给出。Python
问题描述
我通过对 OWM API 的请求获取有关某个城市当前天气的信息:
response = requests.get(
f'https://api.openweathermap.org/data/2.5/weather?q={city}&appid={KEY}&units=metric')
content = json.loads(response.text)
weather_info = {'degrees': f"{content['main']['temp']}",
'state': f"{content['weather'][0]['main']}",
'city': f"{content['name']}",
'timezone': f"{content['timezone']}",
'id': f"{city.id}"}
当我打印weather_info
得到这个 JSON 响应时(例如,城市是纽约):
{'degrees': '9.64', 'state': 'Clouds', 'city': 'New York', 'timezone': '-14400', 'id': '2'}
那么,如何通过在此响应('timezone': '-14400'
)中给出的时区获取纽约的当前时间?
解决方案
这可以通过以下方式完成datetime
:
import datetime
def get_date(timezone):
tz = datetime.timezone(datetime.timedelta(seconds=int(timezone)))
return datetime.datetime.now(tz = tz).strftime("%m/%d/%Y, %H:%M:%S") #strftime is just for visually formatting the datetime object
weather_info = {'degrees': f"{content['main']['temp']}",
'state': f"{content['weather'][0]['main']}",
'city': f"{content['name']}",
'timezone': f"{get_date(content['timezone'])}",
'id': f"{city.id}"}
推荐阅读
- python - 我如何使用 python 获取 Roborock 真空机器人地图位置
- mongodb - 如何使 mongodb 与 countDocuments() 和 $addFields 一起工作
- gradle - 如何在 gradle exec 中使用正则表达式?
- ios - 点击删除控件后关闭表格视图单元格中的删除确认
- python - 如何将这个基于pyautogui的python脚本转换为python3.9中的exe文件?
- sql - SQL 聚合函数,内连接
- java - java中String[]返回值形式的问题
- plot - python 数据必须有方差才能计算内核密度估计误差
- java - 如何仅在 Web 请求中 @Autowire 一个 RequestScoped bean
- macos - 如何在 Flutter 的资产中获取二进制文件?