在本教程中,我們將討論如何編寫一個 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 代碼來查找兩個給定日期之間的總天數的兩種不同方法。
原創文章,作者:OSARI,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/128574.html