datetime.timedelta对象代表两个时间之间的的时间差,两个date或datetime对象相减时可以返回一个timedelta对象。
time1 # datetime.datetime(2018, 7, 18, 21, 28, 27, 680453)
c=datetime.now()-time1
type(c) #
c # datetime.timedelta(0, 1517, 641731)
getattr(c,'days') # 0 getattr(c,'year') #datetime.timedelta' object has no attribute 'year'
c.days #0 c.seconds #1517 c.microseconds #641731
class datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
内部只存储days,seconds,microseconds,
from datetime import datetime,timedelta
time1=datetime.now()
time1 #datetime.datetime(2018, 7, 18, 21, 28, 27, 680453)
b=time1.strftime("%y-%m-%d %H:%M:%S")
b #'18-07-18 21:28:27'
#1小时之后
t2=time1+timedelta(hours=1)
t2 # datetime.datetime(2018, 7, 18, 22, 28, 27, 680453)
#两天之后
datetime.now()+timedelta(2) #datetime.datetime(2018, 7, 20, 21, 37, 10, 286485)
a=datetime(2011,11,12,15,20,25,30)
a.year #2011
a.month # 11
a.day # 12
a.hour #15
a.minute #20
a.second #25
a.microsecond # 30
def get_time_dif(start_time):
"""获取已使用时间"""
end_time = time.time()
time_dif = end_time - start_time
# time.time() 返回的 1970纪元后经过的浮点秒数
return timedelta(seconds=int(round(time_dif)))