In Python, you can work with durations 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 adds a duration of 2 days, 3 hours, and 30 minutes to a datetime object:
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) |
In this code, we create a datetime object representing March 14th, 2023 at 1:30:45 PM. We then define a duration of 2 days, 3 hours, and 30 minutes as a timedelta object. We add this duration to the datetime object using the + operator, which returns a new datetime object representing the result. Finally, we print the new datetime object using the print() function.
You can also subtract a duration from a datetime object using the - operator, or compare two datetime objects to get the duration between them as a timedelta object. Here are some examples:
# Subtract a duration of 1 week from the datetime objectnew_datetime_obj = datetime_obj - timedelta(weeks=1)# Get the duration between two datetime objectsduration = new_datetime_obj - datetime_objprint('Duration:', duration) |
In these examples, we subtract a duration of 1 week from the datetime object using the - operator, and get the duration between two datetime objects using the - operator, which returns a timedelta object representing the result.