• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar

Justin Joyce

Practical tips and tutorials about software development.

  • Standing Invitation
  • Featured Posts
  • Latest
  • About

Calculate Date Difference in Python

Posted Jan 28, 2023 โ€” Updated Jan 10, 2024

Getting the difference between two dates or datetime objects in python is delightfully straightforward; you can just subtract them!

For date objects

from datetime import date

first_date = date(2021, 1, 1)
second_date = date(2022, 1, 1)

diff = second_date - first_date
# datetime.timedelta(days=365)

diff.days # 365

The subtraction returns an object of class timedelta, which has a few handy properties like .seconds and .days. If using whole date objects however, only the .days property will matter. Since there’s no information about the time, seconds can’t be compared.

For datetime objects

The process of getting the diff is exactly the same, but the timedelta object will have a bit more information.

datetime1 = datetime.fromisoformat("2021-11-26T07:18:59")
datetime2 = datetime.fromisoformat("2022-09-13T13:52:19")

diff2 = datetime2 - datetime1
# datetime.timedelta(days=291, seconds=23600)

Since these are datetime objects, the resulting timedelta also has a difference in seconds. This seconds difference is the difference in seconds between the two times only, not between the entire datetime; in this case, that’s the difference between 7:18:59 and 13:52:19. There is also a timedelta.total_seconds() method, which will get the entire difference between the two objects in seconds (and also works on date comparisons):

diff2.total_seconds() # 25166000.0

It’s worth noting that timedelta only gives you days, seconds, and microseconds as options; if you want minutes or hours you have to multiply.


Related Links

  • Calculate date difference in javascript – justinjoyce.dev
  • Timedelta objects – python official docs
  • fromisoformat – python official docs

Filed Under: Dates, Python

Primary Sidebar

Recent Posts

  • Every Built-In Vim Color Scheme (with screenshots)
  • Reverse a string in Python
  • Meeting Cost Calculator
  • Vim find and replace
  • What makes an effective development team

Categories

  • Arrays (5)
  • Command Line (9)
  • Dates (3)
  • Featured (7)
  • Git (7)
  • Golang (5)
  • Javascript (8)
  • Productivity (8)
  • Projects (4)
  • Python (15)
  • Regex (2)
  • Ruby (3)
  • Shell (2)
  • Thoughts (2)
  • Tips (11)
  • Tools (3)
  • Tutorials (1)
  • Vim (4)

Archives

  • July 2024 (1)
  • February 2024 (1)
  • January 2024 (1)
  • December 2023 (1)
  • November 2023 (1)
  • October 2023 (4)
  • September 2023 (1)
  • August 2023 (2)
  • July 2023 (5)
  • June 2023 (3)
  • May 2023 (6)
  • April 2023 (5)
  • March 2023 (5)
  • February 2023 (10)
  • January 2023 (6)
  • December 2022 (7)

Copyright © 2025 ยท Contact me at justin [at] {this domain}

  • Privacy Policy