将长度为13的Unix时间戳字符串转换为可读日期(Python)

3

我正在尝试将此UNIX时间戳1491613677888转换为可读日期。 在这里找到(stackoverflow)python脚本:

import datetime
print(
    datetime.datetime.fromtimestamp(
    int("1284101485")
    ).strftime('%Y-%m-%d %H:%M:%S')
)

但是当我把我的时间戳放在那里时,我遇到了这个错误:
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument

现在我发现我使用的时间戳比应有的多了3个字符。 我在这个链接上进行了检查: http://www.unixtimestamp.com/index.php

并且看到它从中获取时间。 我该如何在Python中实现这个功能呢? (我正在使用Python 3.4版本)


1
无法重现(python2.7 + 3) - Arount
2
你的时间戳中最后的888是从哪里来的?第一个部分 1491613677 是 2017-04-08T01:07:57+00:00,这可能是你想要的。有了它,你的代码可以完美运行。 - Thierry Lathuille
2
你是从某个以毫秒为单位输出的函数中获取它的吗? - Thierry Lathuille
2
当我在Python 2上使用int("1284101485888")时,会收到ValueError: year is out of range错误;而在Python 3.6上则会得到42661-07-22 17:11:28的结果。 - cdarke
关于@ThierryLathuille的评论。是的,我需要毫秒。 我如何在Python 3.4中使用它? - Gil Hadad
2个回答

7

你的timestamp不是“经典”的Unix时间戳(自1970年1月1日以来的秒数),因为它是以毫秒为单位表示的。

可以这样翻译:

import datetime

timestamp_with_ms = 1491613677888

# We separate the 'ordinary' timestamp and the milliseconds
timestamp, ms = divmod(timestamp_with_ms, 1000)
#1491613677 888

# We create the datetime from the timestamp, we must add the 
# milliseconds separately
dt = datetime.datetime.fromtimestamp(timestamp) + datetime.timedelta(milliseconds=ms)


formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# With Python 3.6, you could use:
# formatted_time = dt.isoformat(sep=' ', timespec='milliseconds')

print(formatted_time)
# 2017-04-08 03:07:57.888

编辑:我没有注意到fromtimestamp可以接受一个浮点数。所以,我们可以简单地这样做:

import datetime
timestamp_with_ms = 1491613677888

dt = datetime.datetime.fromtimestamp(timestamp_with_ms / 1000)

formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# With Python 3.6, you could use:
# formatted_time = dt.isoformat(sep=' ', timespec='milliseconds')

print(formatted_time)
# 2017-04-08 03:07:57.888

2
你的时间戳比标准 Unix 时间戳多了 3 个字符?这意味着你的时间戳至少比今天未来 40,000 年。否则,最后 3 个字符可能代表其他内容,例如毫秒,但这不能解释你遇到的错误。
如果这 3 个字符是毫秒,并且看起来你没有在格式字符串中使用它们,那么直接去掉这些字符应该不会有影响。
standard_unix_ts = int("1284101485000"[:-3])

编辑 考虑到@cdarke的评论,我建议改为:

standard_unix_ts = int("1284101485000"[:10])

编辑2 根据吉尔的评论

import datetime

not_unix_ts = "1284101485088"
unix_ts, milliseconds = not_unix_ts[:10], not_unix_ts[10:]
dt = datetime.datetime.fromtimestamp(float(unix_ts))
FORMAT_STRING = '%Y-%m-%d %H:%M:%S'
print("%s and %s milliseconds" % (dt.strftime(FORMAT_STRING), milliseconds))

只是一个想法,取前10个字符可能比去掉最后3个字符更安全,以防有正确长度的时间戳。 - cdarke
非常有价值的评论,我完全同意。 - smassey
在我添加的链接中,我看到了毫秒 - 而且我需要它们。那个时间戳是键的一部分。我需要全部内容。那么如何在Python 3.4中获取毫秒? - Gil Hadad
将它们从字符串中简单剥离,即可获得一个实时时间戳,最后3个字符代表您的毫秒数。再次强调:Unix 时间戳不包含毫秒,因此库在解析它们时会出现问题。我已经准备好了答案,以更好地说明这一点。 - smassey

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接