将 unix 时间戳字符串转换为可读日期

新手上路,请多包涵

我在 Python 中有一个表示 unix 时间戳(即“1284101485”)的字符串,我想将其转换为可读日期。当我使用 time.strftime 时,我得到一个 TypeError

 >>>import time
>>>print time.strftime("%B %d %Y", "1284101485")

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str

原文由 VeryNewToPython 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 281
1 个回答

使用 datetime 模块:

 from datetime import datetime
ts = int('1284101485')

# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))

原文由 Michał Niklas 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题