In this article, we will see what is “timedelta” in python. We will also discuss python timedelta to seconds conversion. But before that, first, we will understand how we can manage dates and times in python. We will take a look at the python DateTime Module and why it is needed. So, Let’s get started,
DateTime Module
When we work on some real-time application in computer programming, we often need to handle date and time more frequently and carefully as it has its challenges. However, python doesn’t have any predefined datatypes to manage them. To overcome this difficulty, python has its inbuilt package named “DateTime Module“. It has different predefined classes that can be used according to our needs. Let us discuss each of them in brief.
Date Class
The object of this class is used to represent dates in yyyy-mm-dd format. However, instantiating objects of this class needs some parameters to pass as arguments. Those arguments may be positional in nature, or they can also be used as keywords. Year, Months, or Days can be the parameters of the object.
Syntax
from datetime import date
obj = date(<arg1>,<arg2>,<arg3>)
obj2 = date(year=<value>, month=<value> , day=<value>)
Let’s see an example,
from datetime import date
date_obj = date(2020,11,26) # parameters as positional arguments
print("Print date for positional arguments:",date_obj)
# Let's check datatype of date_obj
print("Datatype of date_obj: ",type(date_obj))
# parameters as keyword arguments
date_obj2 = date(year = 2021, month=3, day = 26 )
print("Print date for keyword arguments:",date_obj2)
Output:
Print date for positional arguments: 2020-11-26
Datatype of date_obj: <class 'datetime.date'>
Print date for keyword arguments: 2021-03-26
In the above example, it is essential to pass the arguments as the integer; it raises a type error. Date class has many more predefined functions to make our work easier.
Refer here to learn “Best Ways in Python to Import Classes From Another File“
Time Class
The object of this class represents time irrespective of dates or days. We need to pass the hour, minute, and second as parameters to instantiate its object. We can pass it as a keyword argument or positional argument, to be more specific. However, instantiating it without any argument makes an object of “00:00:00” time.
Syntax:
from datetime import time
obj = time(<arg1>,<arg2>,<arg3>)
obj2 = time(hours=<value>, minutes=<value>,seconds=<value>)
It can also take microseconds, tzinfo (default=None), or fold as parameters. Let’s see an example;
from datetime import time
time_obj = time(14,36,16) # parameters as positional arguments
print("Print time:",time_obj)
# Let's check datatype of time_obj
print("Datatype of time_obj: ",type(time_obj))
# parameters as keyword arguments
time_obj2 = time(hour=3, minute= 26, second = 14 )
print("Print time:",time_obj2)
Output:
Print time: 14:36:16
Datatype of time_obj: <class 'datetime.time'>
Print time: 03:26:14
DateTime Class
This class can be seen as a combination of both “Date” and “Time” classes. This class is often used during handling dates and times simultaneously. The object of this class can be instantiated by passing arguments of the date class followed by time class as the positional arguments. However, if you don’t want to care about positions, you can define them as keywords also. There are also several predefined functions to make our work easier. We will not have a more detailed discussion about this as we have already discussed both two classes separately.
TimeDelta Class
This class is convenient and is used for several purposes. It is used for several purposes like arithmetic operations or modulo operations with date and time. To understand it more clearly, we can say that we have to work on intervals and manipulate dates and times using that in real intentions. The timedelta class makes it easier for us. We will discuss examples in a few seconds, but before that, let’s discuss Python Timedelta to Seconds Conversion.
Syntax:
class datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
Although we put these many arguments, it stores only days, seconds, and microseconds internally. Accessing other attributes like hours or minutes will cause an Attribute Error. Let’s look at an example for it,
Example 1:
from datetime import timedelta
# passing time interval as arguments in timedelta object
delta = timedelta(days=49, seconds=21, microseconds=20, milliseconds=29000, minutes=50, hours=18, weeks=21)
print("Printing delta object",delta)
#Accessing different attributes of time interval
print("Number of days",delta.days,"\nNumber of seconds", delta.seconds,"\nNumber of microseconds", delta.microseconds)
# Accessing other parameters which are not defined in timedelta class
# It raises Attribute error
print("\nNumber of hours", delta.hours)
Output:
Printing delta object 196 days, 18:50:50.000020
Number of days 196
Number of seconds 67850
Number of microseconds 20
Traceback (most recent call last):
File "file4.py", line 13, in <module>
print("\nNumber of hours", delta.hours)
AttributeError: 'datetime.timedelta' object has no attribute 'hours'
Once we understand the representation of timedelta, let’s see the attributes and functions provided by the Timedelta class and how to use them. Let’s discuss them one by one.
Python Timedelta to Seconds Conversion
We can get the difference between the two dates in the form of seconds also. All we have to use is timedelta class and “total_seconds()” functions. Let’s understand it with an example,
Timedelta to seconds conversion using total_seconds() method
from datetime import timedelta
# passing time interval as arguments in timedelta object
delta = timedelta(days=49, seconds=21, microseconds=20, milliseconds=29000, minutes=50, hours=18, weeks=21)
print("Printing delta object",delta)
# Converting timedelta to seconds
print("Time delta in seconds",delta.total_seconds())
Output:
Printing delta object 196 days, 18:50:50.000020
Time delta in seconds 17002250.00002
Difference between two timestamps
It yields us time differences between two timestamps.
from datetime import datetime,timedelta
time_obj1 = datetime(2020,11,26,14,36,16,) # parameters as positional arguments
print("Print time1:",time_obj1)
time_obj2 = datetime(2021,10,6,10,34,10,) # parameters as positional arguments
print("Print time2:",time_obj2)
# Let's try to get difference between two dates and check its datatype
time_diff = time_obj2 - time_obj1
print("Time difference in number of days and time:- ",time_diff)
print("Datatype of time_diff: ",type(time_diff))
# Converting time_diff into seconds
print("Time difference in seconds:- ",time_diff.total_seconds(),"seconds")
Output:
Print time1: 2020-11-26 14:36:16
Print time2: 2021-10-06 10:34:10
Time difference in number of days and time:- 313 days, 19:57:54
"Datatype of time_diff: " <class 'datetime.timedelta'>
Time difference in seconds:- 27115074.0 seconds
Adding timedelta to any timestamp
It yields us the final timestamp after adding delta to the initial timestamp.
from datetime import timedelta,datetime
# passing time interval as arguments in timedelta object
delta = timedelta(days=49, seconds=21, microseconds=00, milliseconds=29000, minutes=50, hours=18, weeks=21)
print("Printing delta object",delta)
init_time = datetime(2021,10,6,10,34,10,) # parameters as positional arguments
print("Printing init_time:",init_time)
print("Printing final_time:",delta+init_time)
Output:
Printing delta object 196 days, 18:50:50
Printing init_time: 2021-10-06 10:34:10
Printing final_time: 2022-04-21 05:25:00
Multiplying values to timedelta
It yields an increase in timedelta
from datetime import timedelta,datetime
# passing time interval as arguments in timedelta object
delta = timedelta(days=49, seconds=21, microseconds=00, milliseconds=29000, minutes=50, hours=18, weeks=21)
print("Printing delta object",delta)
init_time = datetime(2021,10,6,10,34,10,) # parameters as positional arguments
print("Printing init_time:",init_time)
print("Multiplying delta yields, increase it by number of times (delta * 4)",delta*4)
Output:
Printing delta object 196 days, 18:50:50
Printing init_time: 2021-10-06 10:34:10
Multuplying delta yields increase it bye number of times (delta * 4) 787 days, 3:23:20
Dividing values to timedelta
from datetime import timedelta,datetime
# passing time interval as arguments in timedelta object
delta = timedelta(days=49, seconds=21, microseconds=00, milliseconds=29000, minutes=50, hours=18, weeks=21)
print("Printing delta object",delta)
init_time = datetime(2021,10,6,10,34,10,) # parameters as positional arguments
print("Printing init_time:",init_time)
print("Dividing delta yields, decrease it by number of times (delta / 4)",delta/4)
Output:
Printing delta object 196 days, 18:50:50
Printing init_time: 2021-10-06 10:34:10
Dividing delta yields, decrease it by number of times (delta / 4) 49 days, 4:42:42.500000
+t1 and -t1 in Timedelta
from datetime import datetime,timedelta
time_obj1 = datetime(2020,11,26,14,36,16,) # parameters as positional arguments
print("Print time:",time_obj1)
time_obj2 = datetime(2021,10,6,10,34,10,) # parameters as positional arguments
print("Print time:",time_obj2)
# Let's try to get difference between two dates and check its datatype
time_diff = time_obj1 - time_obj2
print("Time difference in number of days and time:- ",time_diff)
print(type(time_diff))
# Converting time_diff into seconds
# Here, time is negative representing, future date is subtracted in respect from first date
print("Time difference in seconds:- ",time_diff.total_seconds(),"seconds")
# We can convert it into positive date by adding following operation
print("Converting negative timedelta to positive", -time_diff)
Output:
Print time: 2020-11-26 14:36:16
Print time: 2021-10-06 10:34:10
Time difference in number of days and time:- -314 days, 4:02:06
<class 'datetime.timedelta'>
Time difference in seconds:- -27115074.0 seconds
Converting negative timedelta to positive 313 days, 19:57:54
Modulo Operator (t1 = t2 % t3) in Timedelta
The remainder of two timedelta objects is calculated using the modulo operator.
from datetime import timedelta
# passing time interval as arguments in timedelta object
delta1 = timedelta(days=30)
print("Printing delta object",delta1)
delta2 = timedelta(days=62)
print("Printing delta object",delta2)
delta3 = delta2 % delta1
print(delta3)
Output:
from datetime import timedelta
# passing time interval as arguments in timedelta object
delta1 = timedelta(days=30)
print("Printing delta object",delta1)
delta2 = timedelta(days=62)
print("Printing delta object",delta2)
delta3 = delta2 % delta1
print(delta3)
q, r = divmod(t1, t2) function in Timedelta
from datetime import timedelta
# passing time interval as arguments in timedelta object
delta1 = timedelta(days=30,hours=3, minutes= 26)
print("Printing delta object",delta1)
delta2 = timedelta(days=62,hours=5, minutes= 00)
print("Printing delta object",delta2)
q, r = divmod(delta2, delta1)
print(q) # Prints quotient of given delta i.e only number of days in integers
print(r) # Prints modulo operations over given delta
Output:
Printing delta object 30 days, 3:26:00
Printing delta object 62 days, 5:00:00
2
1 day, 22:08:00
abs(delta), str(delta), repr(delta) in Timedelta
from datetime import time, timedelta
# passing time interval as arguments in timedelta object
delta = timedelta(days=49, seconds=21, microseconds=20, milliseconds=29000, minutes=50, hours=18, weeks=21)
print("Printing delta object",delta)
# #Accessing different attributes of time interval
# print("Number of days",delta.days,"\nNumber of seconds", delta.seconds,"\nNumber of microseconds", delta.microseconds)
print("Converting timedelta object to string object:",str(delta))
print("Checking type after conversion",type(str(delta)))
negative_delta = -delta
print(abs(negative_delta)) # returns postive timedelta for timedelta < 0 and timedelta >0
print(repr(delta))
print("Checking type of timedelta class",type(repr(delta)))
Output:
Printing delta object 196 days, 18:50:50.000020
196 days, 18:50:50.000020
<class 'str'>
196 days, 18:50:50.000020
datetime.timedelta(days=196, seconds=67850, microseconds=20)
<class 'str'>
Conclusion
So, In this article, we discussed something about the DateTime Module. We discussed how we could handle dates and times while python programming. We also discussed which classes are present in the DateTime Module and what are their basic functionalities. After that, we discussed how we can use timedelta class in our programming and how it helps in operations with date and time.
I hope this article has helped you. Keep supporting. Thank You