Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract Two DateTime objects - Python [duplicate]

Tags:

I have two date time objects like this

a = first date time object b = second date time object 

And then

c = a - b 

Now I want to compare c and check if the difference was greater than 3 hours, so I have a time object called three_hours

three_hours = datetime.time(3,0) if c >= three_hours:      #do stuff 

but I get an error saying cannot compare datetime.teimdelta to datetime.time

My question is different as I also want to then compare the subtracted time, not just get the difference!!

How can I convert them to the correct formats so I can check if 3 hours has passed?

Thanks for the help

like image 353
spen123 Avatar asked Aug 25 '15 18:08

spen123


People also ask

Can we subtract two datetime objects in python?

Subtraction of two datetime objects in Python:It is allowed to subtract one datetime object from another datetime object. The resultant object from subtraction of two datetime objects is an object of type timedelta.

How do you find the difference between two datetime objects in python?

timedelta() method. To find the difference between two dates in Python, one can use the timedelta class which is present in the datetime library. The timedelta class stores the difference between two datetime objects.

How can you find the difference in time between two datetime objects time_1 and time_2?

Subtracting the later time from the first time difference = later_time - first_time creates a datetime object that only holds the difference.

How do I get Timedelta in Python?

timedelta() function. Python timedelta() function is present under datetime library which is generally used for calculating differences in dates and also can be used for date manipulations in Python. It is one of the easiest ways to perform date manipulations.


2 Answers

When you subtract two datetime objects in python, you get a datetime.timedelta object. You can then get the total_seconds() for that timedelta object and check if that is greater than 3*3600 , which is the number of seconds for 3 hours. Example -

>>> a = datetime.datetime.now() >>> b = datetime.datetime(2015,8,25,0,0,0,0) >>> c = a - b >>> c.total_seconds() 87062.729491 >>> c.total_seconds() > 3*3600 True 
like image 123
Anand S Kumar Avatar answered Oct 03 '22 19:10

Anand S Kumar


You can also just compare to another timedelta object

import datetime if c >= datetime.timedelta(hours=3):    #do something 
like image 34
NightShadeQueen Avatar answered Oct 03 '22 18:10

NightShadeQueen