将unix时间戳字符串转换为Python中的可读日期 [英] Converting unix timestamp string to readable date in Python

查看:524
本文介绍了将unix时间戳字符串转换为Python中的可读日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get a 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


推荐答案

使用 datetime module:

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

在此代码 datetime.datetime 可能看起来很奇怪,但第一个 datetime 是模块名,第二个是类名。所以 datetime.datetime.fromtimestamp() fromtimestamp()方法 datetime class from datetime module。

In this code datetime.datetime can look strange, but 1st datetime is module name and 2nd is class name. So datetime.datetime.fromtimestamp() is fromtimestamp() method of datetime class from datetime module.

这篇关于将unix时间戳字符串转换为Python中的可读日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆