Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Computing the Number of Days Between Two Dates in Python

Computing the Number of Days Between Two Dates in Python

Document Object Reference Manual Python3 Examples

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

print

(

"The difference in days between the two dates is:"

,

delta.

days

)

Code analysis:

  1. from datetime import date: from the datetime module, import the date class to represent dates.
  2. date1 = date(2023, 10, 1) and date2 = date(2023, 10, 15): define two date objects representing October 1, 2023 and October 15, 2023.
  3. delta = date2 - date1: compute the difference between the two dates; the result is a timedelta object representing the time difference between the two dates.
  4. delta.days: from the timedelta object.
  5. print("两个日期之间的天数差是:", delta.days): output the difference in days between the two dates.

Output result:

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

Document Object Reference Manual Python3 Examples