代码如下:
import time
import datetime
t = time.time()
print (t) #原始时间数据
print (int(t)) #秒级时间戳
print (int(round(t * 1000))) #毫秒级时间戳
nowTime = lambda:int(round(t * 1000))
print (nowTime()); #毫秒级时间戳,基于lambda
print (datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')) #日期格式化
结果:
1552267863.7501628
1552267863
1552267863750
1552267863750
2019-03-11 09:31:03
时间格式说明:
方法代码:
import time
def getTime(seconds):
timeArray = time.localtime(seconds)
otherStyleTime = time.strftime("%H:%M:%S", timeArray)
print(otherStyleTime)
if __name__ == '__main__':
time = getTime(1551863258)
print(time)
结果:
17:07:38
Process finished with exit code 0
上面例子中的%H:%M:%S
可以根据需要设置为别的格式,如%Y_%m_%d %H:%M:%S
;
示例代码:
import time
import datetime
def composeTime(time1):
time2 = datetime.datetime.strptime(time1, "%Y_%m_%d %H:%M:%S")
time3 = time.mktime(time2.timetuple())
time4 = int(time3)
return time4
if __name__ == '__main__':
time = composeTime("2019_03_06 17:07:38")
print(time)
结果:
1551863258
Process finished with exit code 0
说明:上面代码中之所以加了个int(time3)
是因为time3的值其实是1551863258.0
,故以此方法来去掉后边的小数点;