Calculate the number of days between two dates using Python

Document 对象参考手册Python3 Example

We will use Python'sdatetimemodule to calculate the number of days between two dates.datetimeThe module provides classes for handling dates and times. We can use thedateclass to represent dates, and calculate the number of days between two dates through simple subtraction.

Example

from datetime import date

# Define two dates
date1 = date(2023, 10, 1)
date2 = date(2023, 10, 15)

# Calculate the date difference
delta = date2 - date1

# Output the number of days difference
print("The number of days between the two dates is:", delta.days)

Code explanation:

  1. from datetime import date: Import thedatetimeclass from thedatemodule, used to represent dates.
  2. date1 = date(2023, 10, 1)anddate2 = date(2023, 10, 15): Define two date objects, representing October 1, 2023 and October 15, 2023 respectively.
  3. delta = date2 - date1: Calculate the difference between the two dates, resulting in atimedeltaobject, representing the time difference between the two dates.
  4. delta.days: From thetimedeltaExtract the number of days difference from the object.
  5. print("两个日期之间的天数差是:", delta.days): Output the number of days difference between the two dates.

Output result:

两个日期之间的天数差是: 14

Document 对象参考手册Python3 Example

Other extensions