Python - Timedelta object with negative values

Python - Timedelta object with negative values

In Python, the timedelta object from the datetime module can represent a duration, the difference between two dates or times. It can hold both positive and negative values.

Here's how to create a timedelta object with negative values:

from datetime import timedelta # Create a negative timedelta negative_timedelta = timedelta(days=-5, hours=-3, minutes=-10) print(negative_timedelta) # Prints: -6 days, 20:50:00 

In the example above, the timedelta object represents a duration of -5 days, -3 hours, and -10 minutes. Note that when printed, Python normalizes the negative timedelta to a more readable format. In this case, it subtracts 3 hours and 10 minutes from -5 days to give -6 days plus 20 hours and 50 minutes.

You can also create negative timedelta objects by subtracting a later datetime from an earlier one:

from datetime import datetime # Define two datetime objects dt1 = datetime(2022, 1, 10) dt2 = datetime(2022, 1, 5) # Subtract the later datetime from the earlier datetime negative_timedelta = dt2 - dt1 print(negative_timedelta) # Prints: -5 days, 0:00:00 

Here, subtracting dt1 (January 10) from dt2 (January 5) results in a timedelta of -5 days.


More Tags

openhardwaremonitor control-panel razor-pages django-manage.py user-controls mongotemplate bi-publisher select-options pyspark onmousedown

More Programming Guides

Other Guides

More Programming Examples