如何在Python中對當前時間應用偏移量?


無論何時想要對日期/時間進行加減(應用偏移量),都應該使用datetime.datetime(),然後加減datetime.timedelta()例項。 timedelta物件表示持續時間,即兩個日期或時間之間的差值。timedelta建構函式具有以下函式簽名:

datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])

注意 - 所有引數都是可選的,預設為0。引數可以是整數、長整數或浮點數,可以是正數或負數。 你可以在這裡瞭解更多資訊:https://docs.python.club.tw/2/library/datetime.html#timedelta-objects

示例

使用timedelta物件和日期的示例:

import datetime
old_time = datetime.datetime.now()
print(old_time)
new_time = old_time - datetime.timedelta(hours=2, minutes=10)
print(new_time)

輸出

這將給出以下輸出:

2018-01-04 11:09:00.694602
2018-01-04 08:59:00.694602

timedelta() 算術運算不支援datetime.time() 物件;如果需要使用現有datetime.time()物件的偏移量,只需使用datetime.datetime.combine()來形成一個datetime.datetime()例項,進行計算,然後使用.time()方法再次“提取”時間。

更新於:2023年11月4日

4K+ 次瀏覽

啟動你的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.