例如:转换Unix时间戳STR和STR到UNIX时间戳在python
我想转换UNIX时间戳1385629728
为str "2013-11-28 17:08:48"
,
和转换STR "2013-11-28 17:08:48"
到UNIX时间戳1385629728
。
例如:转换Unix时间戳STR和STR到UNIX时间戳在python
我想转换UNIX时间戳1385629728
为str "2013-11-28 17:08:48"
,
和转换STR "2013-11-28 17:08:48"
到UNIX时间戳1385629728
。
做它,如下:
#-*-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()
import time
# where epoch is your epoch time value
time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.localtime(epoch))
您应该使用日期时间。
>>> 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
请避免直接在SO上询问有关谷歌的问题。它降低了平均问题的标准。 – erbdex