PYnative

Python Programming

  • Learn Python
  • Exercises
  • Quizzes
  • Code Editor
  • Tricks
Home » Python » Python DateTime » Python Difference Between Two Dates in Days

Python Difference Between Two Dates in Days

Updated on: October 7, 2022 | Leave a Comment

After reading this article, you’ll learn how to find the difference between two dates in Python. Also, we’ll see how to calculate the number of days between two dates and datetime objects.

Table of contents

  • How to Calculate Difference Between Two Dates in Days
    • Example: Days between two dates
  • Difference between two date object
  • Difference between two datetime object

How to Calculate Difference Between Two Dates in Days

Dates can be in any form, such as string, date object, or datetime object. we will see the example of all cases.

Python provides the datetime module to create and manipulate the date and time. The below steps show how to use the datetime module to calculate the difference between two dates in days.

  1. Import datetime module

    Python datetime module provides various functions to create and manipulate the date and time. Use the from datetime import datetime statement to import a datetime class from a datetime module.

  2. Convert date string to a datetime object

    There may be a case in which dates are in a string format. Before calculating the difference in days, we need to convert both date strings to a datetime object.
    Use the strptime(date_str, format) function to convert a date string into a datetime object as per the corresponding format.
    The format codes are standard directives for mentioning the format of the string for parsing. For example, the %Y/%m/%d format codes are for yyyy-mm-dd

  3. Subtract the date2 from date1

    To get the difference between two dates, subtract date2 from date1. A result is a timedelta object. The timedelta represents a duration which is the difference between two dates, time, or datetime instances, to the microsecond resolution.

  4. Get a difference in days

    To get the number of days between two dates, use the timedelta.days attribute

  5. Get the difference in seconds

    To get a result in seconds, use the timedelta.seconds attribute

Example: Days between two dates

from datetime import datetime

# dates in string format
str_d1 = '2021/10/20'
str_d2 = '2022/2/20'

# convert string to date object
d1 = datetime.strptime(str_d1, "%Y/%m/%d")
d2 = datetime.strptime(str_d2, "%Y/%m/%d")

# difference between dates in timedelta
delta = d2 - d1
print(f'Difference is {delta.days} days')

Output:

Difference is 123 days

Shortcode:

from datetime import datetime as dt

res = (dt.strptime('2022/2/20', "%Y/%m/%d") - dt.strptime('2021/10/20', "%Y/%m/%d")).days

Also, see:

  • Difference between the two dates in months.
  • Time Difference between two-time in Python.
  • Calculate the business days between two dates in Python.

Difference between two date object

There are cases in which you receive dates in a date object instead of a string. In such cases, you can directly calculate the difference between them by performing the subtraction operation.

Example:

from datetime import date

def get_difference(date1, date2):
    delta = date2 - date1
    return delta.days

d1 = date(2021, 10, 20)
d2 = date(2022, 2, 20)
days = get_difference(d1, d2)
print(f'Difference is {days} days')

Output:

Difference is 123 days

Difference between two datetime object

We need to work with a datetime object instead of a date in some cases. The datetime object contains both date (year-month-day) and time (hours-minutes-seconds) information. Let’s see how to calculate the number of days between two datetime objects.

  • First, convert a datetime string to a datetime object using the strptime() function
  • Next, calculate the difference by subtracting datetime1 from datetime2.

Example:

from datetime import datetime

# datetime in string format
str_dt1 = '2021/10/20 09:15:32.36980'
str_dt2 = '2022/2/20 04:25:42.120450'

# convert string to datetime
dt1 = datetime.strptime(str_dt1, "%Y/%m/%d %H:%M:%S.%f")
dt2 = datetime.strptime(str_dt2, "%Y/%m/%d %H:%M:%S.%f")

# difference between datetime in timedelta
delta = dt2 - dt1
print(f'Difference is {delta.days} days')

Output:

Difference is 122 days

Note:

The Python timedelta object considers 24 hours as one day, and For calendar days, you’ll need to round down to the nearest day by removing the partial day on both sides. I.e., we need to set hour, minute, and seconds to zero in both datetime.

Example:

from datetime import datetime

# datetime in string format
str_dt1 = '2021/10/20 09:15:32.36980'
str_dt2 = '2022/2/20 04:25:42.120450'

# convert string to datetime
dt1 = datetime.strptime(str_dt1, "%Y/%m/%d %H:%M:%S.%f")
dt2 = datetime.strptime(str_dt2, "%Y/%m/%d %H:%M:%S.%f")

rounded_dt1 = dt1.replace(hour=0, minute=0, second=0, microsecond=0)
rounded_dt2 = dt2.replace(hour=0, minute=0, second=0, microsecond=0)
delta = (rounded_dt2 - rounded_dt1)
print(delta.days)

Filed Under: Python, Python DateTime

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

TweetF  sharein  shareP  Pin

About Vishal

Founder of PYnative.com I am a Python developer and I love to write articles to help developers. Follow me on Twitter. All the best for your future Python endeavors!

Related Tutorial Topics:

Python Python DateTime

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ
Exercises
Quizzes

Leave a Reply Cancel reply

your email address will NOT be published. all comments are moderated according to our comment policy.

Use <pre> tag for posting code. E.g. <pre> Your code </pre>

Posted In

Python Python DateTime
TweetF  sharein  shareP  Pin

  Python DateTime

  • Python DateTime Guide
  • Python Get Current DateTime
  • Python DateTime Formatting
  • Python String to DateTime
  • Python Timestamp
  • Python Timedelta
  • Python TimeZones
  • List All TimeZones in Python

All Python Topics

Python Basics Python Exercises Python Quizzes Python File Handling Python OOP Python Date and Time Python Random Python Regex Python Pandas Python Databases Python MySQL Python PostgreSQL Python SQLite Python JSON

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

  • Learn Python
  • Python Basics
  • Python Databases
  • Python Exercises
  • Python Quizzes
  • Online Python Code Editor
  • Python Tricks

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

  • Twitter
  • Facebook
  • Sitemap

Legal Stuff

  • About Us
  • Contact Us

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com