Python time模塊時間轉換
阿新 • • 發佈:2018-06-20
localtime yago mon 字符串 TE upd time模塊 mktime months 獲取當前時間
獲取當前時間戳
time_now = int(time.time()) #時間戳
# 1529461333
格式化時間
import time
current_time=time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time()))
current_hour=time.strftime(‘%H‘,time.localtime(time.time()))
#輸出格式: ‘2018-06-20 10:20:19‘
數據庫datetime格式支持。
current_time=time.strftime(‘%Y-%m-%d %H:%M:%S‘,time.localtime(time.time())) #在數據庫中,字段可以是varchar而不是datetime
將時間戳轉為時間
a=1490931508
time.strftime(‘%Y-%m-%d %H:%M:%S‘, time.localtime(a))
將時間轉為時間戳
c=‘2017-03-31 11:38:28‘
d=time.strptime(c,‘%Y-%m-%d %H:%M:%S‘)
time.mktime(d)
JSON序列化mysql裏datetime字段
from bson import json_util import json json.dumps(anObject, default=json_util.default) json.loads(aJsonString, object_hook=json_util.object_hook)
時間運算:
方法一:
time1 = datetime.datetime.now()
time2 = datetime.datetime.now()
seconds = (time2 - time1).seconds
print ‘seconds‘,seconds
方法二:
#先獲得時間數組格式的日期 oneDayAgo = (datetime.datetime.now() - datetime.timedelta(days = 1)) #minutes, days, months, #轉換為時間戳: timeStamp = int(time.mktime(oneDayAgo.timetuple())) #轉換為其他字符串格式: time1 = oneDayAgo.strftime("%Y-%m-%d %H:%M:%S") time2 = host.update_time if time2 > time1: print "正常" else: print "未上報"
Python time模塊時間轉換