w3resource

Python: Get days between two dates

Python Datetime: Exercise-18 with Solution

Write a Python program to get days between two dates.

Sample Solution:

Python Code:

# Import the date class from the datetime module
from datetime import date

# Create a date object representing February 28, 2000 and assign it to variable 'a'
a = date(2000, 2, 28)

# Create a date object representing February 28, 2001 and assign it to variable 'b'
b = date(2001, 2, 28)

# Print the difference between the dates 'b' and 'a'
print(b - a)

Output:

366 days, 0:00:00 

Explanation:

In the exercise above,

  • The code imports the "date" class from the "datetime" module.
  • Creating date objects:
    • It creates two date objects:
      • 'a' representing February 28, 2000.
      • 'b' representing February 28, 2001.
  • Calculating the date difference:
    • It calculates the difference between the two dates (b - a), which results in a 'timedelta' object representing the duration between the two dates
  • Finally, it prints the difference between the two dates, which is the duration between February 28, 2000, and February 28, 2001.

Flowchart:

Flowchart: Get days between two dates.

Python Code Editor:

Contribute your code and comments through Disqus.

Previous: Write a Python program to drop microseconds from datetime.
Next: Write a Python program to get the date of the last Tuesday.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.