您的位置:

Python 程序:查找两个给定日期之间的天数

在本教程中,我们将讨论如何编写一个 Python 程序来查找两个给定数字之间的天数。

假设我们给出了两个日期,我们的预期输出将是:

示例:


Input: Date_1 = 12/10/2021, Date_2 = 31/08/2022
Output: Number of Days between the given Dates are: 323 days
Input: Date_1 = 10/09/2023, Date_2 = 04/02/2025
Output: Number of Days between the given Dates are: 323 days: 513 days

方法 1:天真的方法

在这种方法中,天真的解决方案将从 date_1 开始,它将继续计算天数,直到到达 date_2。该解决方案将需要超过 O(1) 次。这是一个计算 date_1 之前的总天数的简单解决方案,这意味着它将计算从 00/00/0000 到 date_1 的总天数,然后它将计算 date_2 之前的总天数。最后,它将以两个给定日期之间的总天数的形式返回两个计数之间的差异。

示例:


# First, we will create a class for dates
class date_n:
    def __init__(self, day, month, year):
        self.day = day
        self.month = month
        self.year = year

# For storng number of days in all months from
# January to December.
month_Days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]

# This function will count the number of leap years from 00/00/0000 to the #given date

def count_Leap_Years(day):

    years = day.year

    # Now, it will check if the current year should be considered for the count          # of leap years or not.
    if (day.month <= 2):
        years -= 1

    # The condition for an year is a leap year: if te year is a multiple of 4, and a            # multiple of 400 but not a multiple of 100.
    return int(years / 4) - int(years / 100) + int(years / 400)

# This function will return number of days between two given dates
def get_difference(date_1, date_2):

    # Now, it will count total number of days before first date "date_1"

    # Then, it will initialize the count by using years and day
    n_1 = date_1.year * 365 + date_1.day

    # then, it will add days for months in the given date
    for K in range(0, date_1.month - 1):
        n_1 += month_Days[K]

    # As every leap year is of 366 days, we will add 
    # a day for every leap year
    n_1 += count_Leap_Years(date_1)

    # SIMILARLY, it will count total number of days before second date "date_2"

    n_2 = date_2.year * 365 + date_2.day
    for K in range(0, date_2.month - 1):
        n_2 += month_Days[K]
    n_2 += count_Leap_Years(date_2)

    # Then, it will return the difference between two counts
    return (n_2 - n_1)

# Driver program
date_1 = date_n(12, 10, 2021)
date_2 = date_n(30, 8, 2022)

print ("Number of Days between the given Dates are: ", get_difference(date_1, date_2), "days")

输出:

Number of Days between the given Dates are:  322 days

方法 2:使用 Python 日期时间模块

在这个方法中,我们将看到如何使用 Python 的内置函数“datetime”,它可以帮助用户解决各种日期时间相关的问题。为了找出两个日期之间的差异,我们可以以日期类型格式输入两个日期并减去它们,这将导致输出两个给定日期之间的天数。

示例:


from datetime import date as date_n

def number_of_days(date_1, date_2):
    return (date_2 - date_1).days

# Driver program
date_1 = date_n(2023, 9, 10)
date_2 = date_n(2025, 2, 4)
print ("Number of Days between the given Dates are: ", number_of_days(date_1, date_2), "days")

输出:

Number of Days between the given Dates are:  513 days

结论

在本教程中,我们讨论了如何编写 python 代码来查找两个给定日期之间的总天数的两种不同方法。