【问题标题】:How to convert microsecond timestamp to readable date?如何在 Python 中将微秒时间戳转换为可读日期?
【发布时间】:2020-10-20 14:29:28
【问题描述】:

我想转换以下时间戳 - “1571299045371875”,以微秒为单位

转换为“2019-10-17T07:57:35.333333Z”的日期格式。

我尝试过使用:

            date_time = datetime.utcfromtimestamp(timestamp)
            st = date_time.strftime("%Y-%m-%dT%H:%M:%S.%fZ")

但是在尝试转换时间戳时,这给了我“[Errno 22] Invalid argument”。 转换毫秒的时间戳可以正常工作,但我不能失去精度。

有没有办法转换微秒时间戳?

【问题讨论】:

  • 您似乎希望输出类似于 UTC,对吗?

标签: python python-3.x timestamp


【解决方案1】:

将微秒转换为秒,然后您可以使用fromtimestamp() 将自 UNIX 纪元以来的秒数转换为日期时间对象。

import datetime
timestamp_microseconds = 1571299045371875
timestamp_seconds = timestamp_microseconds/1000000
dobj = datetime.datetime.fromtimestamp(timestamp_seconds)
print(dobj.isoformat())

datetime.datetime(2019, 10, 17, 16, 57, 25, 371875) '2019-10-17T16:57:25.371875'

正如 MrFuppes 所说,这将根据机器的本地时间返回一个日期时间对象。

来自文档: https://docs.python.org/3/library/datetime.html#datetime.datetime.fromtimestamp

datetime.fromtimestamp() 返回POSIX时间戳对应的本地日期时间, 例如由 time.time() 返回。如果可选参数 "tz" 为 None 或 未指定,时间戳转换为平台的本地日期 和时间,返回的 datetime 对象是幼稚的。

【讨论】:

  • @DeividasLiveris:请注意,如果您希望输出引用 UTC,这不是您应该做的
  • @MrFuppes,是的,我为此使用 datetime.utcfromtimestamp,但这帮助我意识到我不需要将微秒作为参数传递给微秒。
【解决方案2】:

根据您的预期输出,您应该使用类似于 UTC 的日期时间对象:

from datetime import datetime, timezone

ts = 1571299045371875
dtobj = datetime.fromtimestamp(ts/1e6, tz=timezone.utc)
# datetime.datetime(2019, 10, 17, 7, 57, 25, 371875, tzinfo=datetime.timezone.utc)

isostring = dtobj.isoformat()
# '2019-10-17T07:57:25.371875+00:00'

# or as specified in the question
isostring = dtobj.isoformat().replace('+00:00', 'Z')
# '2019-10-17T07:57:25.371875Z'

【讨论】:

    猜你喜欢
    • 2012-09-17
    • 2011-04-14
    • 1970-01-01
    • 2018-12-02
    • 1970-01-01
    • 2021-12-30
    • 1970-01-01
    • 1970-01-01
    • 2019-07-27
    相关资源
    最近更新 更多