技术文章和资源

技术文章(时间排序)

热门类别

Python PHP MySQL JDBC Linux

用于检查日期范围内日期的 Python 程序

pythonserver side programmingprogramming

在本文中,我们将学习如何检查给定的输入日期是否在指定的日期范围内。有很多方法可以做到这一点;其中一些方法已详细说明。

使用 datetime 模块

Datetime 模块提供用于操作日期和时间的类。该模块提供各种函数和方法,例如日期、时间、日期时间、时间增量、最小年份、最大年份、UTC 等。

在本文中,我们将使用 datetime 模块的 datetime() 函数。 datetime() 接受日期、月份和年份作为输入参数,并返回日期作为输出。

示例

在此示例中,我们将使用 datetime 模块的 datetime() 函数检查日期 25−05−2023 是否在 01−01−1991 和 31−12−2023 的日期范围内。

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,日期范围定义为 01-01-1995 和 09−12−2020。以下是代码。

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.

相关文章