【问题标题】:convert timestamp to date in custom commands在自定义命令中将时间戳转换为日期
【发布时间】:2021-12-04 22:51:17
【问题描述】:

我正在 django 中创建自定义命令。我在使用 fromtimestamp 等方法将时间戳转换为日期时遇到问题。我有这样的错误: 第 13 行,在句柄中 timest_conv = datetime.fromtimestamp(timest) OSError: [Errno 22] 无效参数

这是我的带把手的课

class Command(BaseCommand):
    def handle(self, *args , **options):
        r = requests.get('https://api.metals.live/v1/spot/silver').json()
        price = r[0]['price']
        timest = r[0]['timestamp']
        timest_conv = datetime.fromtimestamp(timest)
        print(price,timest, timest_conv )

        return

【问题讨论】:

  • r[0]['timestamp'] 是什么样的?
  • 最后一个1634309968403
  • 当我将它转换为 int(r[0]['timestamp']) 错误是一样的

标签: python django add-custom-command


【解决方案1】:

时间戳以 1970 年 1 月 1 日以来的 毫秒 表示。因此,您应该将这些除以 1'000 以检索时间戳:

timest_conv = datetime.fromtimestamp(<strong>int(timest)/1000</strong>)

对于给定的示例时间戳,我们得到:

>>> datetime.fromtimestamp(1634309968403/1000)
datetime.datetime(2021, 10, 15, 16, 59, 28, 403000)

【讨论】:

  • 感谢它完美运行
猜你喜欢
  • 1970-01-01
  • 2016-11-26
  • 2023-03-11
  • 2012-12-03
  • 1970-01-01
  • 1970-01-01
  • 2020-10-19
  • 1970-01-01
相关资源
最近更新 更多