python学习:time、unixtime、string的转换

时间:2024-03-04 10:45:11

1、String转换成time类:

import time
endTimeStr = "2015-11-28 00:00:00"
formatStr = "%Y-%m-%d %H:%M:%S"
tmObject = time.strptime(startTimeStr, formatStr)

2、time转换成String类:

timeStr = time.strftime("%Y/%m/%d %H:%M:%S", tmObject)

3、获取unix_timestamp:
不能直接从string获取timestamp,需要先转换成time类或者datetime类。以转成time类为例:

import time
endTimeStr = "2015-11-28 00:00:00"
formatStr = "%Y-%m-%d %H:%M:%S"
tmObject = time.strptime(startTimeStr, formatStr)
tmStamp = time.mktime(tmObject)

4、时间戳转换成字符串, 类似mysql的from_unixtime操作:

import time
tmStamp = 1447315020
tmObject = time.localtime(timeStamp)
tmStr = time.strftime("%Y-%m-%d %H:%M:%S", tmObject)