Python程式檢查日期是否在日期範圍內


在本文中,我們將學習如何檢查給定的輸入日期是否在指定的日期範圍內。有很多方法可以做到這一點;其中一些方法將在下文中詳細解釋。

使用datetime模組

Datetime模組提供用於操作日期和時間的類。此模組提供各種函式和方法,例如date、time、datetime、timedelta、minyear、maxyear、UTC等。

在本文中,我們將使用datetime模組的datetime()函式。datetime()接受日期、月份和年份作為輸入引數,並返回日期作為輸出。

示例

在這個例子中,我們將使用datetime模組的datetime()函式來檢查日期25-05-2023是否在1991-01-01和2023-12-31的日期範圍內。

from datetime import datetime
def is_date_in_range(date, start_date, end_date):
   return start_date <= date <= end_date
date = datetime(2023, 5, 25)
start_date = datetime(1991, 1, 1)
end_date = datetime(2023, 12, 31)
if is_date_in_range(date, start_date, end_date):
   print("Date is within the range.")
else:
   print("Date is outside the range.")

輸出

Date is within the range.

使用date()函式

在datetime模組中,我們還有另一個函式date(),它接受日期、月份和年份作為輸入引數,構建日期並將其作為輸出返回。

示例

在這個例子中,我們建立了一個名為is_date_in_range()的函式,並將輸入日期、開始日期和結束日期作為輸入引數,以及檢查日期是否在給定範圍內條件。日期使用datetime模組的date()函式給出。

from datetime import date
def is_date_in_range(input_date, start_date, end_date):
   return start_date <= input_date <= end_date
input_date = date(2023, 5, 10)
start_date = date(2023, 1, 1)
end_date = date(2023, 12, 31)
if is_date_in_range(input_date, start_date, end_date):
   print(input_date,"is within the range.")
else:	
   print(input_date,"is outside the range.")

輸出

2023-05-10 is within the range.

使用字串比較

字串是一種資料結構,它將資料儲存在單引號或雙引號中。字串使用str()函式定義,將任何資料型別元素作為輸入,並返回字串作為輸出。

在這裡,要檢查給定日期是否在給定的日期範圍內,我們將比較以字串格式定義的日期。

示例

在這個例子中,我們將日期定義為字串格式,然後將輸入字串與定義的日期範圍內的日期進行比較。

假設給定的輸入日期為25-05-2023,日期範圍定義為1995-01-01和2020-09-12。以下是程式碼。

def is_date_in_range(date, start_date, end_date):
   return start_date <= date <= end_date
date = "2023-05-25"
start_date = "1995-01-01"
end_date = "2023-12-09"
if is_date_in_range(date, start_date, end_date):
   print(date,"is within the range.")
else:
   print(date,"is outside the range.")

輸出

2023-05-25 is within the range.

更新於:2023年10月19日

2K+ 瀏覽量

啟動你的職業生涯

透過完成課程獲得認證

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