The Wayback Machine - https://web.archive.org/web/20240808185647/https://www.geeksforgeeks.org/python-datetime-timedelta-function/
Open In App

Python | datetime.timedelta() function

Last Updated : 20 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report

Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations. 

Syntax : datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) 
Returns : Date

Code #1: 

Python
# Timedelta function demonstration 

from datetime import datetime, timedelta


# Using current time
ini_time_for_now = datetime.now()

# printing initial_date
print ("initial_date", str(ini_time_for_now))

# Calculating future dates
# for two years
future_date_after_2yrs = ini_time_for_now + \
                        timedelta(days = 730)

future_date_after_2days = ini_time_for_now + \
                         timedelta(days = 2)

# printing calculated future_dates
print('future_date_after_2yrs:', str(future_date_after_2yrs))
print('future_date_after_2days:', str(future_date_after_2days))

Output
initial_date 2019-02-27 12:41:45.018389
future_date_after_2yrs: 2021-02-26 12:41:45.018389
future_date_after_2days: 2019-03-01 12:41:45.018389


Code #2: 

Python
# Timedelta function demonstration 
from datetime import datetime, timedelta


# Using current time
ini_time_for_now = datetime.now()

# printing initial_date
print ('initial_date:', str(ini_time_for_now))

# Calculating past dates
# for two years
past_date_before_2yrs = ini_time_for_now - \
                       timedelta(days = 730)

# for two hours
past_date_before_2hours = ini_time_for_now - \
                        timedelta(hours = 2)


# printing calculated past_dates
print('past_date_before_2yrs:', str(past_date_before_2yrs))
print('past_date_before_2hours:', str(past_date_before_2hours))

Output
initial_date 2019-02-27 12:41:46.104662
past_date_before_2yrs: 2017-02-27 12:41:46.104662
past_date_after_2days: 2019-02-27 10:41:46.104662


Code #3: 

Python
# Timedelta function demonstration 
from datetime import datetime, timedelta

# Using current time
ini_time_for_now = datetime.now()

# printing initial_date
print ("initial_date", str(ini_time_for_now))

# Some another datetime
new_final_time = ini_time_for_now + \
                 timedelta(days = 2)

# printing new final_date
print ("new_final_time", str(new_final_time))


# printing calculated past_dates
print('Time difference:', str(new_final_time - \
                             ini_time_for_now))

Output
initial_date 2019-02-27 12:41:47.386595
new_final_time 2019-03-01 12:41:47.386595
Time difference: 2 days, 0:00:00

Subtracting a timedelta object from a date or datetime object:

Approach:

Create a timedelta object with the desired time difference.
Subtract the timedelta object from a date or datetime object using the – operator.

Python
import datetime

today = datetime.date.today()
three_days_ago = today - datetime.timedelta(days=3)

print("Today:", today)
print("Three days ago:", three_days_ago)

Output
Today: 2023-03-24
Three days ago: 2023-03-21

Time complexity: O(1)
Auxiliary Space: O(1)

Python | datetime.timedelta() function- FAQs

What does timedelta() return in Python?

In Python, timedelta() is a constructor function from the datetime module that returns a timedelta object. This object represents a duration, or the difference between two dates or times.

How to find timedelta in Python?

To create a timedelta object in Python, you typically subtract one datetime object from another. Here’s an example:

from datetime import datetime, timedelta
# Create two datetime objects
start_time = datetime(2024, 6, 1, 12, 0, 0)
end_time = datetime(2024, 6, 10, 14, 30, 0)
# Calculate timedelta
duration = end_time - start_time
print(duration) # Output: 9 days, 2:30:00

How to compare 2 datetime in Python?

You can compare two datetime objects using comparison operators (<, <=, >, >=, ==, !=).

from datetime import datetime
# Create two datetime objects
date1 = datetime(2024, 6, 1)
date2 = datetime(2024, 6, 10)
# Compare datetime objects
if date1 < date2:
print("date1 is earlier than date2")
elif date1 > date2:
print("date1 is later than date2")
else:
print("date1 and date2 are equal")

How to get time from timedelta?

You can access the time components (days, hours, minutes, seconds) from a timedelta object using its attributes: .days, .seconds, and .microseconds. Here’s an example:

from datetime import timedelta
# Create a timedelta object
duration = timedelta(days=5, hours=3, minutes=30)
# Get the total seconds
total_seconds = duration.total_seconds()
print("Total seconds:", total_seconds)
# Get individual components
days = duration.days
hours = duration.seconds // 3600 # Convert seconds to hours
minutes = (duration.seconds // 60) % 60 # Convert remaining seconds to minutes
seconds = duration.seconds % 60
print(f"Days: {days}, Hours: {hours}, Minutes: {minutes}, Seconds: {seconds}")

What is the alternative to Timedelta in Python?

There isn’t a direct alternative to timedelta for representing durations between dates or times in Python’s standard library. timedelta is specifically designed for this purpose and is part of the datetime module. However, you can use libraries like arrow, dateutil, or pendulum for more advanced date and time manipulations, which may offer additional features or easier syntax for handling durations and intervals.

import arrow
# Example with arrow library
start = arrow.get('2024-06-01')
end = arrow.get('2024-06-10')
duration = end - start
print(duration) # Output: 9 days, 0:00:00


Previous Article
Next Article

Similar Reads

Python DateTime - Timedelta Class
Timedelta class is used for calculating differences between dates and represents a duration. The difference can both be positive as well as negative. Syntax: class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0) Example: C/C++ Code # Timedelta function demonstration from datetime import datetime, t
4 min read
Using Timedelta and Period to create DateTime based indexes in Pandas
Real life data often consists of date and time-based records. From weather data to measuring some other metrics in big organizations they often rely on associating the observed data with some timestamp for evaluating the performance over time. We have already discussed how to manipulate date and time in pandas, now let's see the concepts of Timesta
3 min read
Python | Pandas Timedelta.floor()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Python | Pandas Timedelta.asm8
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Python | Pandas Timedelta.components
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
2 min read
Python | Pandas Timedelta.days
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Python | Pandas Timedelta.delta
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Python | Pandas Timedelta.nanoseconds
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Python | Pandas Timedelta.microseconds
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Python | Pandas Timedelta.ceil()
Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Timedelta is a subclass of datetime.timedelta, and behaves in a similar manner. It is the pandas equivalent of python’s datetime.timedel
1 min read
Article Tags :
Practice Tags :
three90RightbarBannerImg