In Python, you can represent a negative duration using a timedelta object with negative arguments. For example, here's how you can create a timedelta object representing a duration of -1 day:
from datetime import timedeltaduration = timedelta(days=-1)print('Duration:', duration) |
In this code, we create a timedelta object representing a duration of -1 day by passing a negative value for the days argument to the timedelta() constructor. We then print the timedelta object using the print() function.
You can perform arithmetic operations on negative timedelta objects just like you can with positive timedelta objects. For example, you can add a negative duration to a datetime object to subtract time from it:
from datetime import datetime, timedelta# Create a datetime objectdatetime_obj = datetime(2023, 3, 14, 13, 30, 45)# Define a negative duration of 1 daynegative_duration = timedelta(days=-1)# Subtract the duration from the datetime objectnew_datetime_obj = datetime_obj + negative_durationprint('New datetime object:', new_datetime_obj) |
In this code, we subtract a duration of 1 day from a datetime object by creating a negative timedelta object with a value of -1 for the days argument, and then adding it to the datetime object using the + operator. The result is a new datetime object representing the same time 1 day earlier.