【问题标题】:Trying to convert UNIX Epoch time into Normal date from JSON尝试将 UNIX 纪元时间从 JSON 转换为正常日期
【发布时间】:2021-08-08 01:36:11
【问题描述】:

我正在尝试将 unix 纪元时间从 JSON 转换为正常日期。

JSON 代码(不完整):

{"success":true,"lastUpdated":1621365664405

我有这个代码:

import requests
import json
from datetime import datetime

r = requests.get('https://api.hypixel.net/skyblock/bazaar').json()

#last updated datetime
time = r['lastUpdated']
datetime_time = datetime.fromtimestamp(time).strftime('%Y-%m-%d')

print(datetime_time)

但我收到以下错误:第 9 行,在 datetime_time = datetime.fromtimestamp(time).strftime('%Y-%m-%d')。 OSError: [Errno 22] 无效参数

【问题讨论】:

  • 请调试并找到产生错误的行。
  • 编辑问题
  • r['lastUpdated'] 实际上是什么样子的?
  • 编辑了问题。

标签: python json python-3.x datetime


【解决方案1】:

返回的时间戳以毫秒为单位,而您需要的是以秒为单位的时间戳。我认为只需将“时间”除以 1000 就可以了。 希望对您有所帮助!

编辑: 此外,您不需要使用 strftime。以下也应该有效:

# Import the whole datetime module
import datetime as dt

time = r['lastUpdated'] / 1000
# Use the date module, instead of the datetime module
datetime_time = str(dt.date.fromtimestamp(time))

这将以您想要的格式返回您的字符串。使用您喜欢的任何一个。

你想要的代码可以是:

time = r['lastUpdated'] / 1000

只要改变了那条线,它应该可以工作。 希望对您有所帮助!

【讨论】:

  • 欢迎您!作为建议,请始终检查返回的对象的类型,因为正如其他人指出的那样,错误可能来自作为字符串返回的时间戳。并且 python 时间戳以秒为单位工作,因此如果返回的时间戳以毫秒甚至纳秒为单位,则必须对其进行转换。我总是使用以下网站查看:epochconverter.com
猜你喜欢
  • 2016-09-15
  • 2013-04-02
  • 2013-01-08
  • 2018-12-27
  • 1970-01-01
  • 2018-08-03
  • 2018-10-01
  • 2019-12-08
相关资源
最近更新 更多