Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/284.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将UNIX时间戳转换为格式为YYYY-MM-DD的日期字符串_Python_Json_Api_Date_Weather - Fatal编程技术网

Python 将UNIX时间戳转换为格式为YYYY-MM-DD的日期字符串

Python 将UNIX时间戳转换为格式为YYYY-MM-DD的日期字符串,python,json,api,date,weather,Python,Json,Api,Date,Weather,我试图在终端打印给定日期(主要是第二天)是否下雨。为此,我已经从rapidapi.com获得了OpenWeatherMap 我将响应转换为json response = requests.request("GET", url, headers=headers, params=querystring) obj = response.text x = json.loads(obj) print(x['list'][0]) #part of output {'dt': 160667

我试图在终端打印给定日期(主要是第二天)是否下雨。为此,我已经从rapidapi.com获得了OpenWeatherMap

我将响应转换为json

response = requests.request("GET", url, headers=headers, params=querystring)
obj = response.text
x = json.loads(obj)
print(x['list'][0])
#part of output
{'dt': 1606676400, 'sunrise': 1606662312, 'sunset': 1606697500,
我认为dt是某种时间,我想把它转换成YYYY-MM-DD格式的日期,但不知道如何转换


谢谢你的帮助,祝你度过愉快的一天

该格式是一种
UNIX时间戳
,顺便说一句,这是一种非常好的共享日期的方法,因为不需要进行广泛的解析,而datetime库提供了一种简单的解析方法

from datetime import datetime

timestamp = 1606662312
dt_object = datetime.fromtimestamp(timestamp)

[1] 29.11.2020 16:05

编辑: 如果需要特定字符串格式的日期,可以使用:

date_string = dt_object.strftime("%Y-%m-%d")
[2] '2020-11-29'
对于感兴趣的读者:

UNIX时间戳

It's pretty common to store date and time as a timestamp in a database. 
A Unix timestamp is the number of seconds between a particular date and 
January 1, 1970 at UTC.

该格式是一个
UNIX时间戳
,顺便说一句,这是一种非常好的共享日期的方法,因为不需要进行广泛的解析,而datetime库提供了一种简单的解析方法

from datetime import datetime

timestamp = 1606662312
dt_object = datetime.fromtimestamp(timestamp)

[1] 29.11.2020 16:05

编辑: 如果需要特定字符串格式的日期,可以使用:

date_string = dt_object.strftime("%Y-%m-%d")
[2] '2020-11-29'
对于感兴趣的读者:

UNIX时间戳

It's pretty common to store date and time as a timestamp in a database. 
A Unix timestamp is the number of seconds between a particular date and 
January 1, 1970 at UTC.

鉴于问题中的
YYYY-MM-DD
输出,这里有一个替代方案(不含时间)-

从解释器中运行-

>>> dt_convert
datetime.date(2020, 11, 29)
>>> str(dt_convert)
'2020-11-29'

鉴于问题中的
YYYY-MM-DD
输出,这里有一个替代方案(不含时间)-

从解释器中运行-

>>> dt_convert
datetime.date(2020, 11, 29)
>>> str(dt_convert)
'2020-11-29'

这个API的文档说明了这些时间戳的格式是什么?我猜是unix时间戳那些是纪元时间这个API的文档说明了这些时间戳的格式是什么?我猜是unix时间戳那些是纪元时间非常感谢。我认为OP要求的格式是使用
strftime
dt\u object.strftime(“%Y-%m-%d”)
非常感谢@yasserkalil,我读过了那部分。我添加了您的答案。
str(…)
本身可以用来缩短时间。我同意,但是
strftime
更为通用,考虑到欧洲国家等国家经常需要的不同格式,加上
str
将包括DateTime的小时和秒。非常感谢您的解释!谢谢。我认为OP要求的格式是使用
strftime
dt\u object.strftime(“%Y-%m-%d”)
非常感谢@yasserkalil,我读过了那部分。我添加了您的答案。
str(…)
本身可以用来缩短时间。我同意,但是
strftime
更为通用,考虑到欧洲国家等国家经常需要的不同格式,加上
str
将包括DateTime的小时和秒。非常感谢您的解释!