如何在Python中對日期進行算術運算?


在本文中,我們將向您展示如何在Python中對日期進行算術運算。現在我們來看5個關於此任務的示例:

  • 向給定日期新增天數

  • 從給定日期減去天數

  • 向給定日期新增天數和小時數

  • 從當前日期減去月份

  • 向給定日期新增年份

示例1:向給定日期新增天數

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 使用import關鍵字匯入**datetime**模組。

  • 輸入日期並建立一個變數來儲存它。

  • 輸入日期格式字串並建立一個變數來儲存它。

  • 使用**strptime()函式**(將字串格式的時間戳格式化為日期時間物件)格式化給定日期,並使用**timedelta()函式**(通常用於計算兩個日期之間的差值。它也可用於操作Python中的日期,此函式使使用者可以非常輕鬆地執行此操作。)向其新增1天。

  • 使用**strftime()函式**(根據格式程式碼返回表示datetime物件的字串)再次格式化新日期,並將新的日期物件和日期格式作為引數傳遞給它。

  • 將舊日期加1後列印新日期。

以下程式返回加1後的給定日期:

# importing datetime module import datetime # input date inputDate = '21-04-2013' # giving the date format date_format = '%d-%m-%Y' # formatting the date using strptime() function and adding 1 day to it date = datetime.datetime.strptime(inputDate, date_format) + datetime.timedelta(days=1) # Formatting the date date=date.strftime(date_format) # Printing the modified date print('New Date after incrementing old date {',inputDate,'} by 1 is:',date)

輸出

New Date after incrementing old date { 21-04-2013 } by 1 is: 22-04-2013

示例2:從給定日期減去天數

這與先前的方法類似,但這次我們從給定日期減去某個隨機數,例如2,如下所示。

以下程式返回減去2後的給定日期:

import datetime # input date inputDate = '21-04-2013' # giving the date format date_format = '%d-%m-%Y' # formatting the date using strptime() function and subtracting 2 days from it date = datetime.datetime.strptime(inputDate, date_format) - datetime.timedelta(days=2) # Formatting the date date=date.strftime(date_format) # Printing the modified date print('New Date after decrementing old date {',inputDate,'} by 2 is:',date)

輸出

New Date after decrementing old date { 21-04-2013 } by 2 is: 19-04-2013

示例3:向給定日期新增天數和小時數

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 使用import關鍵字匯入datetime和timedelta模組

  • 使用**datetime.now()**函式(返回當前本地日期和時間)輸入當前日期和時間,以HH:MM:SS格式獲取當前日期和時間。

  • 透過將天數和小時數作為引數傳遞給timedelta()函式,遞增當前日期,並將此新日期儲存在一個變數中。

  • 將舊日期加一定的天數和小時數後列印新日期。

以下程式返回加一定小時數和天數後的給定日期:

# importing datetime, timedelta modules from datetime import datetime, timedelta # getting the current date and time currentDate = datetime.now() print("The Current Date and Time = ", currentDate) # Incrementing the current date with some random days and hours newDate = currentDate + timedelta(days=4, hours=3) print('New Date:',newDate)

輸出

The Current Date and Time = 2022-09-07 02:26:21.098855
New Date: 2022-09-11 05:26:21.098855

示例4:從當前日期減去月份

演算法(步驟)

以下是執行所需任務的演算法/步驟:

  • 使用import關鍵字匯入datetime和relativedelta模組

  • 使用datetime()函式輸入輸入日期和時間。

  • 列印給定的輸入日期和時間。

  • 透過將月份作為引數傳遞給**relativedelta()**函式(**relativedelta**型別旨在應用於現有的datetime,可用於替換該datetime的特定元件或表示時間間隔)從給定日期減去n個月(例如5)。

  • 從給定日期減去月份後列印新日期。

以下程式返回減去月份後的給定日期:

# importing datetime, relativedelta modules import datetime from dateutil.relativedelta import relativedelta # input date and time in (yy,mm,dd,hh,mm,ss) inputDatetime = datetime.datetime(2019, 9, 12, 8, 40, 7) # printing the input date and time print("Input Date and time = ", inputDatetime) # Subtracting 5 months using the relativedelta function newDate = inputDatetime - relativedelta(months = 5) # Printing the modified date print("5 Months Ago = ", newDate)

輸出

Input Date and time = 2019-09-12 08:40:07
5 Months Ago = 2019-04-12 08:40:07

示例5:向給定日期新增年份

此方法與上述方法相同,但在這種情況下,我們使用relativedelta()函式將給定日期遞增一些任意年份,例如8。

以下程式返回加一定年份後的給定日期:

# importing datetime, relativedelta modules import datetime from dateutil.relativedelta import relativedelta # input date and time in (yy,mm,dd,hh,mm,ss) inputDatetime = datetime.datetime(2019, 9, 12, 8, 40, 7) # printing the input date and time print("Input Date and time = ", inputDatetime) # Incrementing 8 years using the relativedelta function newDate = inputDatetime + relativedelta(years = 8) # Printing the modified date print("After 8 years = ", newDate)

輸出

Input Date and time = 2019-09-12 08:40:07
After 8 years = 2027-09-12 08:40:07

結論

在本文中,我們學習瞭如何使用五個不同的示例對給定日期應用算術運算,例如增加和減少年份、月份、天數和小時數。

更新於:2023年11月2日

7000+ 次瀏覽

啟動您的職業生涯

透過完成課程獲得認證

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