Python timedelta | Difference between two Date, Time, or DateTime

Python timedelta is representing the duration of the difference between two dates, times, or datetime objects. A timedelta is a class and part of datetime modules. This Tutorial, you will understand timedelta function with examples.

Using a timedelta object in python is easy because it supports mathematical operation (Arithmetic operation), such as addition, multiplication, subtraction etc.

Python timedelta | Difference between two Date, Time, or DateTime examples

Before you start if you don’t have knowledge about Python datetime module then must read the following topics :

Syntax

The default value of all arguments is 0 and also optional. The Arguments value can be integers (numbers) or floats and may be positive or negative.

Python timedelta example

You have to import class datetime and timedelta from in-built datetime module for this example. In this example, we are adding 365 days in the current date.

Output:

Difference between two Date and Time

We are an import only datetime module in this example. Using a timedelta class to get the difference between days and times.

Output: Current time : 4 days, 1:24:00
End time : 5 days, 6:26:00
Difference : 1 day, 5:02:00

Convert a timedelta to minutes

Here is an example how to get minutes using timedelta.

Output: minutes : 62.0

Python timedelta attributes

Here is timedelta class attributes are:

  • timedelta.min– The most negative timedelta object, it’s value is – timedelta(-999999999).
  • timedelta.max – The most positive timedelta object, like this –  timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999).
  • timedelta.resolution– The smallest possible difference between non-equal timedelta objects, timedelta(microseconds=1).

Output: -999999999 days, 0:00:00
999999999 days, 23:59:59.999999
0:00:00.000001

Reference: https://docs.python.org/3/library/datetime.html (Official website)

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6

Python 3.7

All examples Difference between two Date, Time, etc used in timedelta python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.