简体   繁体   English

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

[英]Convert UNIX timestamp to date string with format YYYY-MM-DD

I'm trying to print whether it's going to rain or not for given date (mostly next day) in terminal.我正在尝试在终端打印给定日期(主要是第二天)是否会下雨。 For that I already get OpenWeatherMap from rapidapi.com.为此,我已经从 rapidapi.com 获得了 OpenWeatherMap。

I convert my response to json我将我的回复转换为 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,

and i think the dt is some kind of time, i want to convert it to date in format YYYY-MM-DD, but don't know how.我认为 dt 是某种时间,我想将其转换为 YYYY-MM-DD 格式的日期,但不知道如何。

Thanks for all help, and have a nice day!感谢所有帮助,祝您有美好的一天!

The format is a UNIX timestamp , by the way a very good way of sharing dates, because no extensive parsing is required and datetime library offers an easy way of parsing it格式是UNIX timestamp ,顺便说一下,这是一种非常好的共享日期的方式,因为不需要大量解析,并且 datetime 库提供了一种简单的解析方式

from datetime import datetime

timestamp = 1606662312
dt_object = datetime.fromtimestamp(timestamp)

[1] 29.11.2020 16:05

EDIT: If you then need the date in a particular string format you can use:编辑:如果您需要特定字符串格式的日期,您可以使用:

date_string = dt_object.strftime("%Y-%m-%d")
[2] '2020-11-29'

For the interested reader:对于感兴趣的读者:

UNIX timestamp 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.

Given the output of YYYY-MM-DD in the question, here is an alternative (without the time) -鉴于问题中YYYY-MM-DD的 output ,这里有一个替代方案(没有时间) -

from datetime import date
dt = 1606676400
dt_convert = date.fromtimestamp(dt)

Run from the interpreter -从解释器运行 -

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM