Initialize timedelta Object in Python (4 Examples)

 

In this tutorial, you’ll learn how to initialize a timedelta object in Python programming.

Table of contents:

Let’s dig in:

 

Example Data & Add-On Libraries

First, we need to load the datetime module.

from datetime import timedelta                          # import datetime module

 

Example 1: Initializing via days Input

This example demonstrates how to initialize a timedelta object using “days”.

td_days = timedelta(days=15)                            # initialzing timedelta object
print(td_days)                                          # printing timedelta object
# 15 days, 0:00:00

 

Example 2: Initializing via hours Input

This example demonstrates how to initialize a timedelta object using “hours”.

td_hours = timedelta(hours=20)                          # initialzing timedelta object
print(td_hours)                                         # printing timedelta object
# 20:00:00

 

Example 3: Initializing via weeks, minutes, seconds Inputs

This example illustrates how to initialize a timedelta object using “weeks”, “minutes” and “seconds”.

td_mix = timedelta(weeks = 2.5, minutes=75, seconds=20) # initialzing timedelta object
print(td_mix)                                           # printing timedelta object
# 17 days, 13:15:20

 

Example 4: Initializing via microseconds Input

In this example, I’ll show how to initialize a timedelta object using “microseconds”.

td_microseconds = timedelta(microseconds=3500)         # initialzing timedelta object
print(td_microseconds)                                 # printing timedelta object
# 0:00:00.003500

 

Video, Further Resources & Summary

Have a look at the following video on my YouTube channel. I demonstrate the contents of this tutorial in the video.

 

The YouTube video will be added soon.

 

In addition, you might have a look at some other tutorials on https://statisticsglobe.com/.

 

In this article, you have learned how to generate a timedelta object in the Python programming language. If you have additional comments and/or questions, don’t hesitate to let me know in the comments.

 

Ömer Ekiz Python Programming & Informatics

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.

 

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.

The maximum upload file size: 2 MB. You can upload: image. Drop file here

Top