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


無論何時你想要在日期/時間上增加或減去(應用偏移量),請使用 datetime.datetime(),然後增加或減去 datetime.timedelta() 例項。timedelta 物件表示一個持續時間,即兩個日期或時間之間的差值。timedelta 構造器的函式簽名如下 −

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

注意 −所有論證都是可選的,預設為 0。論證可以是 int、long 或 float,可以是正數或負數。你可以在這裡瞭解更多資訊 − 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() 方法再次“提取”時間。

更新於: 04-11-2023

4K+ 檢視

開啟您的 職業生涯

完成課程以獲得認證

開始
廣告
© . All rights reserved.