Python is a well-known and effective programming language that is frequently used for a wide range of tasks, including data analysis, web development, machine learning, and many others. The datetime module in Python, which offers several classes for interacting with dates and times, is one of the most frequently used modules.
One such class used to indicate durations or discrepancies between two dates or times in Python is the timedelta class.
What does TimeDelta do in Python?
In Python, durations or discrepancies between two dates or times are represented via the timedelta class. It is specified in the datetime module and is a subclass of the datetime class.
A timedelta object displays the amount of time—in days, seconds, and microseconds—that separates two dates or timings. It can be used to carry out a number of operations, including addition, subtraction, multiplication, and division, on dates and times.
Python uses the following syntax to create a timedelta object:
timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Here is an illustration of a Python timedelta object creation:
from datetime import timedelta # create a timedelta object for 1 day one_day = timedelta(days=1) # create a timedelta object for 1 hour one_hour = timedelta(hours=1) # create a timedelta object for 30 minutes thirty_minutes = timedelta(minutes=30)
Python Timedelta Example
Let's examine some usage examples for the Python timedelta class.
Example 1: Converting Datetime Objects into Timedelta Objects
from datetime import datetime, timedelta # get the current date and time now = datetime.now() # create a timedelta object for 1 day one_day = timedelta(days=1) # add the timedelta object to the current date and time next_day = now + one_day # print the current date and time and the next day print("Current Date and Time:", now) print("Next Day:", next_day)
Output:
Current Date and Time: 2023-05-11 16:40:10.478182 Next Day: 2023-05-12 16:40:10.478182
In this example, a timedelta object that represents one day was made using the timedelta class. The following day's date and time were produced by adding this timedelta entity to the present date and time with the + operator.
Example 2: Subtracting from a Datetime Object a Timedelta Object
from datetime import datetime, timedelta # create a datetime object for May 1st, 2023 at 12:00:00 dt = datetime(2023, 5, 1, 12, 0, 0) # create a timedelta object for 5 days five_days = timedelta(days=5) # subtract the timedelta object from the datetime object result = dt - five_days # print the result print(result)
Output:
2023-04-26 12:00:00
The datetime as well as timedelta classes obtained from the datetime module were first imported in this example. A datetime object called dt was then generated for May 1st, 2023, at 12:00:00. Then, a timedelta object five_days was made to represent a five-day period.
Finally, we applied the - operator to subtract the timedelta object five_days from the datetime object dt. A new datetime object reflecting the time and date 5 days prior to May 1st, 2023 was produced as a result. The outcome was then printed.
Parameters of Timedelta Python Function
A timedelta object can be created using the many parameters that the Python timedelta function accepts. The timedelta function can be used with the following parameters:
- Days: The timedelta object's number of days is represented by this argument. It can be an integer that is positive or negative.
- Seconds: The timedelta object's total number of seconds is represented by this argument. It can be an integer that is positive or negative.
- Microseconds: The value of this property indicates how many microseconds are contained in the timedelta object. It can be an integer that is positive or negative.
- Minutes: The timedelta object's minute count is represented by this argument. It can be an integer that is positive or negative.
- Hours: The timedelta object's number of hours is represented by this argument. It can be an integer that is positive or negative.
- Weeks: The timedelta object's number of weeks is represented by this attribute. It can be an integer that is positive or negative.
Here is an illustration of how to create a timedelta object with several parameters:
import datetime # Creating a timedelta object td = datetime.timedelta(days=10, hours=3, minutes=20, seconds=45) # Printing the timedelta object print(td)
Output:
10 days, 3:20:45
How to Calculate Timedelta in Python?
Python programmers frequently use the timedelta function to determine the difference between two dates or timings. An illustration of how to calculate timedelta in Python is provided here:
import datetime # Creating two datetime objects date1 = datetime.datetime(2022, 5, 1) date2 = datetime.datetime(2022, 5, 10) # Calculating the difference between two dates diff = date2 - date1 # Printing the timedelta object print(diff)
Output:
9 days, 0:00:00
To begin, we first build two datetime objects in this example to represent two distinct dates. To obtain a timedelta object that represents the difference between the two dates, we next subtract one datetime object from the other.
What is the difference between Timedelta and Datetime?
The Python datetime module contains both the timedelta and datetime classes. While timedelta is used to represent a period of time, datetime is used to express a specific date and time.
The datetime class provides a number of properties that can be used to obtain the precise date and time, including year, month, day, hour, minute, and second. Timedelta, on the other hand, is limited to durational elements like days, seconds, and microseconds.
Here is an illustration of how datetime and timedelta differ from one another:
import datetime # Creating a datetime object dt = datetime.datetime(2022, 5, 10, 12, 30, 45) # Printing the datetime object print(dt) # Creating a timedelta object td = datetime.timedelta(days=10, hours=3, minutes=20, seconds=45) # Printing the timedelta object print(td) # Adding timedelta to datetime new_dt = dt + td # Printing the updated datetime object print(new_dt) # Subtracting timedelta from datetime new_dt = dt - td # Printing the updated datetime object print(new_dt)
Output:
2022-05-10 12:30:45 10 days, 3:20:45 2022-05-20 15:51:30 2022-04-29 09:10:00
In this illustration, we start by creating a datetime object to represent a particular date and time. The next step is to create a timedelta object, which in this case represents a time period of 10 days, 3 hours, 20 minutes, and 45 seconds.
The timedelta object and the datetime object are then used in two actions. To create a new datetime object with the modified date and time, we first add the timedelta object to the datetime object. The datetime object is then subtracted from the timedelta object to produce another updated datetime object.
To view the results of our activities, we print every datetime and timedelta object at the end.
Conclusion
In this article, we did go through the Python timedelta class's functions, syntax, and usage, as well as some examples that demonstrate how it works. Happy Learning :)