In Python, you can create a timedelta object using the datetime module's timedelta class. A timedelta object represents a duration of time as a number of days, seconds, and microseconds.
Here's an example code that creates a timedelta object representing a duration of 2 days, 3 hours, and 30 minutes:
from datetime import timedelta# Define a duration of 2 days, 3 hours, and 30 minutesduration = timedelta(days=2, hours=3, minutes=30)print('Duration:', duration) |
In this code, we create a timedelta object representing a duration of 2 days, 3 hours, and 30 minutes by passing the number of days, hours, and minutes as arguments to the timedelta() constructor. We then print the timedelta object using the print() function.
You can also create a timedelta object representing a duration of a certain number of seconds or microseconds:
# Define a duration of 500 secondsduration_seconds = timedelta(seconds=500)# Define a duration of 1 microsecondduration_microseconds = timedelta(microseconds=1) |
In these examples, we create timedelta objects representing a duration of 500 seconds and a duration of 1 microsecond by passing the number of seconds or microseconds as arguments to the timedelta() constructor.
You can also perform arithmetic operations on timedelta objects, such as adding or subtracting them from datetime objects, or adding or subtracting them from other timedelta objects:
from datetime import datetime, timedelta# Create a datetime objectdatetime_obj = datetime(2023, 3, 14, 13, 30, 45)# Define a duration of 2 days, 3 hours, and 30 minutesduration = timedelta(days=2, hours=3, minutes=30)# Add the duration to the datetime objectnew_datetime_obj = datetime_obj + durationprint('New datetime object:', new_datetime_obj)# Subtract a duration of 1 week from the datetime objectnew_datetime_obj = datetime_obj - timedelta(weeks=1)print('New datetime object:', new_datetime_obj)# Add two durations togethertotal_duration = duration + timedelta(hours=2, seconds=30)print('Total duration:', total_duration) |
In this code, we perform arithmetic operations on timedelta objects, such as adding a duration to a datetime object using the + operator, subtracting a duration from a datetime object using the - operator, and adding two durations together using the + operator.