在python中将unix timestamp转换为str,将str转换为unix时间戳 timestamp

Convert UNIX timestamp to str and str to UNIX timestamp in python

本问题已经有最佳答案,请猛点这里访问。

例如:

我想把unix时间戳1385629728转换成str "2013-11-28 17:08:48",并将str-"2013-11-28 17:08:48"转换为unix时间戳1385629728


它在下面的:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#-*-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()

你应该使用的日期时间。

1
2
3
4
5
>>> 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


1
2
3
4
5
import time

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

源代码