[Python] Date and Time Calculations: How to Use timedelta

To calculate dates such as “100 days later” or “3 hours ago” in Python, use the timedelta class from the standard datetime module.

By adding or subtracting a timedelta object to a date or datetime object, you can perform accurate calculations that automatically account for calendar details like leap years and month ends.

目次

1. Adding Dates (Calculating Future Dates)

Create a timedelta object and add it to the base date object using the + operator.

Source Code

from datetime import datetime, date, timedelta

# Base date and datetime
base_date = date(2024, 12, 22)
base_datetime = datetime(2024, 12, 22, 12, 0, 30)

# Define the period to add (100 days)
# timedelta accepts: days, seconds, microseconds, milliseconds, minutes, hours, weeks
delta = timedelta(days=100)

# Execute calculation
future_date = base_date + delta
future_datetime = base_datetime + delta

print(f"Base Date           : {base_date}")
print(f"Date 100 days later : {future_date}")
print("-" * 30)
print(f"Base DateTime       : {base_datetime}")
print(f"DateTime 100 days later: {future_datetime}")

Execution Result

Base Date           : 2024-12-22
Date 100 days later : 2025-04-01
------------------------------
Base DateTime       : 2024-12-22 12:00:30
DateTime 100 days later: 2025-04-01 12:00:30

Note: The year changed automatically, and the month was calculated correctly.

2. Subtracting Dates (Calculating Past Dates and Differences)

By using the - operator, you can calculate a date “N days ago” or find the “difference (duration)” between two dates.

Implementation Example: Calculating Elapsed Days

from datetime import datetime

# Past date and time
start_time = datetime(2024, 1, 1, 9, 0, 0)
# Current date and time (using a fixed value for this example)
end_time = datetime(2025, 12, 22, 18, 30, 0)

# Subtracting datetimes results in a timedelta object
elapsed_time = end_time - start_time

print(f"Start : {start_time}")
print(f"End   : {end_time}")
print("-" * 30)
print(f"Duration      : {elapsed_time}")
print(f"Total Days    : {elapsed_time.days} days")
print(f"Total Seconds : {elapsed_time.total_seconds()} seconds")

Execution Result

Start : 2024-01-01 09:00:00
End   : 2025-12-22 18:30:00
------------------------------
Duration      : 721 days, 9:30:00
Total Days    : 721 days
Total Seconds : 62328600.0 seconds

Explanation

Main Arguments of timedelta

You can specify the following arguments in the timedelta constructor (all are optional, default is 0). You can combine them to express flexible durations.

  • days
  • hours
  • minutes
  • seconds
  • weeks

Note: The arguments years and months do not exist in timedelta. If you need to perform calculations based on calendar months or years, it is common to use the external library dateutil.relativedelta.

よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次