在Python中将UNIX时间戳转换为字符串和字符串转换为UNIX时间戳

3
例如:
我想将UNIX时间戳 1385629728 转换为字符串 "2013-11-28 17:08:48"
并将字符串 "2013-11-28 17:08:48" 转换为UNIX时间戳 1385629728

请避免在SO上直接询问可以通过谷歌搜索得到答案的问题。这会降低平均问题的标准。 - erbdex
3个回答

4
请按照以下步骤操作:
#-*-coding:utf-8-*-

import datetime, time

def ts2string(ts, fmt="%Y-%m-%d %H:%M:%S"):
    dt = datetime.datetime.fromtimestamp(ts)
    return dt.strftime(fmt)

def string2ts(string, fmt="%Y-%m-%d %H:%M:%S"):
    dt = datetime.datetime.strptime(string, fmt)
    t_tuple = dt.timetuple()
    return int(time.mktime(t_tuple))

def test():
    ts = 1385629728

    string = ts2string(ts)
    print string

    ts = string2ts(string)
    print ts

if __name__ == '__main__':
    test()

2

你应该使用 datetime。

>>> import datetime
>>> print(datetime.datetime.fromtimestamp(int("1385629728")).strftime('%Y-%m-%d %H:%M:%S'))
2013-11-28 14:38:48
>>> print int(datetime.datetime.strptime('2013-11-28 14:38:48', '%Y-%m-%d %H:%M:%S').strftime("%s"))
1385629728

这种类型的回答我最喜欢了。谢谢! - greg121

0
import time 

# where epoch is your epoch time value 
time.strftime("%a, %d %b %Y %H:%M:%S +0000", 
                        time.localtime(epoch))

源代码


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