【问题标题】:Convert UNIX timestamp to date string with format YYYY-MM-DD将 UNIX 时间戳转换为格式为 YYYY-MM-DD 的日期字符串
【发布时间】:2021-03-11 18:06:44
【问题描述】:

我正在尝试在终端打印给定日期(主要是第二天)是否会下雨。为此,我已经从 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 格式的日期,但不知道如何。

感谢大家的帮助,祝你有美好的一天!

【问题讨论】:

  • 此 API 的文档对这些时间戳的格式有何说明?
  • 我猜它是一个unix时间戳
  • 那是时代

标签: python json api date weather


【解决方案1】:

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

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

从解释器运行 -

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

【讨论】:

    【解决方案2】:

    格式是UNIX timestamp,顺便说一句,这是一种非常好的共享日期的方式,因为不需要进行大量解析,并且日期时间库提供了一种简单的解析方式

    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.
    

    【讨论】:

    • 非常感谢。我认为要获得 OP 要求的格式是使用 strftime 就像 dt_object.strftime("%Y-%m-%d")
    • 非常感谢@YasserKhalil 我重读了那部分。我添加了你的答案
    • str ( ... ) 本身可以用来截断时间。
    • 我同意,但strftime 更通用,允许使用不同的格式,例如经常需要的格式。欧洲国家,加上str 在日期时间的情况下会占用小时和秒
    • 非常感谢您的解释!
    猜你喜欢
    • 1970-01-01
    • 2011-10-05
    • 2023-03-15
    • 2022-08-03
    • 1970-01-01
    • 2014-06-22
    • 2018-05-19
    • 2014-05-02
    • 2017-05-05
    相关资源
    最近更新 更多