Computing the Number of Days Between Two Dates in Python
We will use Python's datetime module to compute the number of days between two dates.datetime module provides classes for handling dates and times; we can use the date class to represent dates and compute the difference in days with a simple subtraction.
Example
from
datetime
import
date
Define two dates
date1
=
date
(
2023
,
10
,
1
)
date2
=
date
(
2023
,
10
,
15
)
Compute the date difference
delta
=
date2 - date1
Output the difference in days
(
"The difference in days between the two dates is:"
,
delta.
days
)
Code analysis:
from datetime import date: from thedatetimemodule, import thedateclass to represent dates.date1 = date(2023, 10, 1)anddate2 = date(2023, 10, 15): define two date objects representing October 1, 2023 and October 15, 2023.delta = date2 - date1: compute the difference between the two dates; the result is atimedeltaobject representing the time difference between the two dates.delta.days: from thetimedeltaobject.print("两个日期之间的天数差是:", delta.days): output the difference in days between the two dates.
Output result:
两个日期之间的天数差是: 14
Python3 Examples