![]() |
VOOZH | about |
Timedelta class is used for calculating differences between dates and represents a duration. The difference can both be positive as well as negative.
Syntax:
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Example:
Difference in dates: 31 days, 0:00:00 Date1 after 4 days: 2020-01-07 00:00:00 Date1 before 15 days: 2019-12-23 00:00:00
Let's see the attributes provided by this class -
| Attribute Name | Description |
|---|---|
| min | minimum value of timedelta object is -999999999 |
| max | maximum value of timedelta object is 999999999 |
| resolution | The minimum possible difference between timedelta objects |
Example: Getting the minimum and maximum value of timedelta objects
Minimum value of timedelta object -999999999 days, 0:00:00 Maximum value of timedelta object 999999999 days, 23:59:59.999999
Output
Minimum value of timedelta object -999999999 days, 0:00:00
Maximum value of timedelta object 999999999 days, 23:59:59.999999
Timedelta class provides only one function which is total_seconds(). This method returns the duration provided by the timedelta object in the number of seconds.
Note: For a duration of more than 270 years this method will be accurate for microseconds.
Example: Getting various duration in seconds
3600.0 60.0 86400.0
| Operator | Description |
|---|---|
| Addition (+) | Adds and returns two timedelta objects |
| Subtraction (-) | Subtracts and returns two timedelta objects |
| Multiplication (*) | Multiplies timedelta object with float or int |
| Division (/) | Divides the timedelta object with float or int |
| Floor division (//) | Divides the timedelta object with float or int and return the int of floor value of the output |
| Modulo (%) | Divides two timedelta object and returns the remainder |
| +(timedelta) | Returns the same timedelta object |
| -(timedelta) | Returns the resultant of -1*timedelta |
| abs(timedelta) | Returns the +(timedelta) if timedelta.days > 1=0 else returns -(timedelta) |
| str(timedelta) | Returns a string in the form (+/-) day[s], HH:MM:SS.UUUUUU |
| repr(timedelta) | Returns the string representation in the form of the constructor call |
Example 1: Performing basic arithmetic operations on timedelta objects.
Original timedelta: 1 day, 0:00:00 After Multiplication: 5 days, 12:00:00 After Subtraction: 4 days, 12:00:00 After Addition: 10 days, 0:00:00 After division: 2 days, 4:48:00 After floor division: 2 days, 18:00:00 After Modulo: 2 days, 12:00:00
Example 2: Getting Absolute value and the string representation of timedelta objects
Original timedelta: 1 day, 0:00:00 After Negation: -1 day, 0:00:00 Absolute Value: 1 day, 0:00:00 String representation: 1 day, 0:00:00 Constructor call: datetime.timedelta(1)
Note: For more information on Python Datetime, refer to Python Datetime Tutorial