# Convert timedelta to Seconds in Python (Example)

This tutorial explains how to convert a timedelta object into seconds in the Python programming language.

The article will consist of these contents:

Letâ€™s jump right to the tutorial!

## Example Data

As a first step, we have to import the datetime module:

`import datetime                                    # Load datetime module`

Letâ€™s also construct some example data:

```dt_1 = datetime.datetime(2023, 12, 5, 10, 30, 47)  # Create first datetime object
print(dt_1)
# 2023-12-05 10:30:47```
```dt_2 = datetime.datetime(2022, 11, 9, 5, 38, 15)   # Create second datetime object
print(dt_2)
# 2022-11-09 05:38:15```

As you can see based on the previous outputs of the Python console, we have just created two datetime objects.

In the next step, Iâ€™m going to subtract those two dates and times from each other:

```td = dt_1 - dt_2                                   # Subtract datetimes
print(td)                                          # Print timedelta object
# 391 days, 4:52:32```

As you can see, our new data object shows 391 days and 4 hours, 52 minutes, and 32 seconds.

Letâ€™s check the data type of this data object:

```print(type(td))                                    # Test data type of data object
# <class 'datetime.timedelta'>```

We have created a timedelta object.

## Example: Transform timedelta Object to Seconds Using total_seconds() Function

The following Python code illustrates how to convert a timedelta object to seconds. For this task, weâ€™ll use the total_seconds function:

```td_sec = td.total_seconds()                        # Apply total_seconds function
print(td_sec)                                      # Print seconds
# 33799952.0```

As you can see, the corresponding seconds to our example timedelta object are shown in the previous output, i.e. 33799952 seconds.

## Video, Further Resources & Summary

Have a look at the following video on my YouTube channel. In the video, I explain the contents of this article in Python.

In addition, you may want to have a look at some of the other articles on this website. Some articles are listed below.

This page was created in collaboration with Ã–mer Ekiz. Have a look at Ã–merâ€™s author page to get more information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.

Subscribe to the Statistics Globe Newsletter