timedelta
timedelta is Python's built-in datetime.timedelta class, exposed inside the formula sandbox as a constructor. Calling it returns a duration object representing a span of time. Use timedelta for date and datetime arithmetic — adding or subtracting days, hours, minutes, or seconds from date/datetime values.
Syntax
timedelta(days=0, seconds=0, minutes=0, hours=0, weeks=0)
All parameters are optional and default to 0. You can combine them.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
| days | int/float | No | Number of days |
| seconds | int/float | No | Number of seconds |
| minutes | int/float | No | Number of minutes (converted to seconds internally) |
| hours | int/float | No | Number of hours (converted to seconds internally) |
| weeks | int/float | No | Number of weeks (converted to days internally) |
Returns
Type: timedelta
A duration object that can be added to or subtracted from date and datetime values.
Properties
| Property | Description | Example |
|---|---|---|
.days |
Total whole days in the duration |
timedelta(hours=48).days returns 2
|
.seconds |
Remaining seconds after whole days (0–86399) |
timedelta(hours=25).seconds returns 3600
|
.total_seconds() |
Total duration expressed in seconds |
timedelta(days=1, hours=12).total_seconds() returns 129600.0
|
Examples
Records from the last 30 days:
datetime.now() - timedelta(days=30)
Records from the last 2 hours:
datetime.now() - timedelta(hours=2)
Add 1 week to a date:
date.today() + timedelta(weeks=1)
Calculate the difference between two dates in days:
(date.today() - date(2024, 1, 1)).days
Check if a record is older than 90 days:
(datetime.now() - datetime.strptime([created_on], '%Y-%m-%d')).days > 90
Combine multiple units:
timedelta(days=1, hours=6, minutes=30)
Creates a duration of 1 day, 6 hours, and 30 minutes.
Notes
-
timedeltacan be added to or subtracted fromdateanddatetimeobjects. - Subtracting two
dateordatetimevalues produces atimedelta. -
timedeltasupports multiplication and division:timedelta(days=1) * 7equalstimedelta(weeks=1). - Negative durations are valid:
timedelta(days=-7)represents 7 days in the past.
Related Documentation
- date — Date-only values
- datetime — Date and time combined
- Working with Types — Overview of all data types
Comments
0 comments
Please sign in to leave a comment.