I have a variable which is <type 'datetime.timedelta'>
and I would like to compare it against certain values.
Lets say d produces this datetime.timedelta
value 0:00:01.782000
I would like to compare it like this:
#if d is greater than 1 minute
if d>1:00:
print "elapsed time is greater than 1 minute"
I have tried converting datetime.timedelta.strptime()
but that does seem to work. Is there an easier way to compare this value?
You can also find the difference between two datetime objects to get a timedelta object and perform the comparison based on the positive or negative value returned by the timedelta. total_seconds() function. if seconds < 0: print('First date is less than the second date.
The Python timedelta is a module that represents the time difference between two points in time. module has functions that allow you to calculate the elapsed seconds, minutes, hours, days, and weeks from one point in time to another.
When you have two datetime objects, the date and time one of them represent could be earlier or latest than that of other, or equal. To compare datetime objects, you can use comparison operators like greater than, less than or equal to.
Python | datetime.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.
We can use the str (timedelta) constructor to print the time delta in the string form [D day [s], ] [H]H:MM:SS [.UUUUUU]. You can also use the __str__ () method on timedelta object to display it in string format
The smallest possible difference between two nonequal time delta objects is 1 microsecond. We can use the week attribute of the timedelta class to add or subtract weeks from a given date to compute future and past dates in Python.
You'll have to create a new timedelta
with the specified amount of time:
d > timedelta(minutes=1)
Or this slightly more complete script will help elaborate:
import datetime
from time import sleep
start = datetime.datetime.now()
sleep(3)
stop = datetime.datetime.now()
elapsed = stop - start
if elapsed > datetime.timedelta(minutes=1):
print "Slept for > 1 minute"
if elapsed > datetime.timedelta(seconds=1):
print "Slept for > 1 second"
Output:
Slept for > 1 second
You just need to create timedelta
object from scratch, comparison after that is trivial:
>>> a = datetime.timedelta(minutes=1)
>>> b = datetime.timedelta(minutes=1, seconds=1)
>>> a < b
True
>>> a > b
False
Correct me if I'm wrong but I think that you could also use the following:
Instead of
if elapsed > datetime.timedelta(seconds=1):
You could say
if elapsed.seconds > 1:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With