Python timedelta With Examples

Python timedelta object is used to perform datetime manipulations in an easy way. The timedelta class is part of datetime module.

Pythoon timedelta

Python timedelta object represents a duration of time. We can create its object using following factory method.

Note that timedelta() function takes keyword arguments. All arguments are optional and default to 0. Arguments may be integers or floats and may be positive or negative.

The timedelta object supports mathematical operations such as addition, subtraction, multiplication etc. using basic operators, so it’s very easy to use it. It’s mostly used to get a datetime object with some delta date and time.

Python timedelta example

Let’s have a look at some examples of getting future dates and past dates using timedelta object.


Python timedelta with date and time

Python timedelta supports addition and subtraction with date object too.


However, timedelta doesn’t support the same operations with time object.

Above code will produce the following error message.

Python timedelta attributes

Python timedelta class has three attributes.


Python timedelta total seconds

Python timedelta object total_seconds() method returns the total number of seconds.

Output: Seconds in an year: 31536000.0

Python timedelta operations

Let’s look at some more operations between timedelta objects.



Python timedelta object is very useful for datetime manipulations. The support for basic arithmetic operators makes it very easy to use.

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: