Python datetime 模組之timedelta
阿新 • • 發佈:2019-02-04
原文地址:http://blog.csdn.net/xinxing__8185/article/details/48022401
timedalte 是datetime中的一個物件,該物件表示兩個時間的差值
建構函式:datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)其中引數都是可選,預設值為0
下面應該是常識,幾乎每個人都知道:
1 millisecond = 1000 microseconds1 minute = 60 seconds
1 hour = 3600 seconds
1 week = 7 days
在建構函式中,引數值的範圍如下:
0 <= microseconds < 10000000 <= seconds < 3600*24 (the number of seconds in one day)
-999999999 <= days <= 999999999
timedalte 有三個只讀屬性:
timedelta.min:負數最大時間差,相當於 timedelta(-999999999)。timedelta.max:正數最大時間差,相當於 timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)。
timedelta.resolution:兩個時間的最小差值 相當於 timedelta(microseconds=1)。
三個只讀屬性例項:
- from datetime import date,timedelta
- print(timedelta.max);#999999999 days, 23:59:59.999999
- print(timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999));#999999999 days, 23:59:59.999999
- print(timedelta.min);#-999999999 days, 0:00:00
- print(timedelta(-999999999));#-999999999 days, 0:00:00
- print(timedelta.resolution);#0:00:00.000001
- print(timedelta(microseconds=1));#0:00:00.000001
timedelta.total_seconds()方法:返回該時間差 以秒為單位的值
綜上的例項:
- from datetime import datetime,date,timedelta
- now = datetime.now();
- nextDay = now + timedelta(days = 1);#增加一天後的時間
- nextSecond = now + timedelta(seconds = 1);#增加一秒後的時間
- span = now - nextDay;#獲取時間差物件
- print(now);
- print(nextDay);
- print(nextSecond);
- print(span.total_seconds());#獲取時間差 以秒為單位