【问题标题】:Unix time to real time in microseconds python [duplicate]Unix时间到实时以微秒为单位python [重复]
【发布时间】:2019-03-13 20:28:13
【问题描述】:

我尝试了以下方法并得到了错误:

>>> datetime.utcfromtimestamp(1539065539).strftime('%Y-%m-%d %H:%M:%S.%f')
'2018-10-09 6:12:19.000000'.
>>> datetime.utcfromtimestamp(int(1539065539013987670)).strftime('%Y-%m-%d %H:%M:%S.%f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
>>> datetime.utcfromtimestamp(153906553901).strftime('%Y-%m-%d %H:%M:%S.%f')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

我认为这个数字超出了int 数据类型的大小。因此,这个错误来了。如何摆脱它并在微秒内得到正确答案,这是我所期待的。

【问题讨论】:

  • 不是“数字超出了 int 的大小”,而是您使用错误的数据调用函数。 “unix 时间戳是一种将时间跟踪为运行总秒数的方法。此计数从 1970 年 1 月 1 日 UTC 的 Unix 纪元开始”,因此您必须使用有效时间戳(以秒为单位)调用 utcfromtimestamp(timestamp)。

标签: python python-3.x datetime time unix-timestamp


【解决方案1】:

将值(实际上似乎是纳秒)除以 1e9 得到秒,您可以将其传递给 utcfromtimestamp。

>>> datetime.datetime.utcfromtimestamp(1539065539013987670 / 1e9)
datetime.datetime(2018, 10, 9, 6, 12, 19, 13988)

【讨论】:

  • 先生,这是一个不错且简洁的答案。谢谢
【解决方案2】:

这是在Python - Convert epoch time with nanoseconds to human-readable?回答的

>>> datetime.utcfromtimestamp(1539065539013987670/1000000000).strftime('%Y-%m-%d %H:%M:%S.%f')
'2018-10-09 06:12:19.013988'

【讨论】:

  • 这也是一个很棒的答案......
猜你喜欢
  • 1970-01-01
  • 2021-11-20
  • 1970-01-01
  • 2020-04-11
  • 2015-07-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-24
相关资源
最近更新 更多