Convert timedelta to Hours in Python (Example)
In this article, you’ll learn how to convert a timedelta object to hours in the Python programming language.
Table of contents:
Let’s jump right to the programming part:
Example Data & Imported Modules
To start our example, we need to import the datetime module.
import datetime # Loading the datetime module
Next, we’ll create data that we can use in the next example:
td = datetime.timedelta(days=33, seconds=100100) # sample timedelta object construction print(td) # printing the sample timedelta # 34 days, 3:48:20
The Python code shows that our exemplifying data is equal to the printed time.
Example: Express timedelta in Hours
The following Python code illustrates how to convert the timedelta object into hours by use of the total_seconds() function.
total_seconds = td.total_seconds() # Convert timedelta into seconds seconds_in_hour = 60 * 60 # Set the number of seconds in an hour td_in_hours = total_seconds / seconds_in_hour # Convert timedelta into hours print(td_in_hours) # Print timedelta in hours # 819.8055555555555
Video, Further Resources & Summary
Have a look at the following video on my YouTube channel. In the video, I illustrate the content of this post.
The YouTube video will be added soon.
Furthermore, you may read the other articles on this website. I have released several tutorials that are related to the conversion of timedelta to hours already.
- Dates & Times in Python – datetime Module
- Introduction to timedelta Objects in Python
- Convert timedelta to Seconds in Python
- Calculate Number of Hours, Minutes & Seconds Between Two datetimes
- Subtract Seconds, Minutes & Hours from datetime in Python
- Add Seconds, Minutes & Hours to datetime Object
- Python Programming Examples
At this point of the article, you should know how to express a timedelta object in hours in the Python programming language. In case you have further questions or comments, please let me know in the comments section below. Besides that, don’t forget to subscribe to my email newsletter to receive regular updates on new articles.
This page was created in collaboration with Ömer Ekiz. Have a look at Ömer’s author page to get further information about his professional background, a list of all his tutorials, as well as an overview on his other tasks on Statistics Globe.