Page 1 of 1

compare times

Posted: Tue May 05, 2015 3:00 pm
by Canedje
I like to compare to time strings to check if the time between is more then 5 minutes.

I use the next code:

Code: Select all

from datetime import datetime
s1 = '21:07'
s2 = '21:16'
delta = datetime.strptime(s2, '%H:%M') - datetime.strptime(s1, '%H:%M')
if (delta.minutes  > 5):
  print ">  5 minuten"
but receive the next errors:

Traceback (most recent call last):
File "thermostaat.py", line 435, in <module>
if (delta.minutes > 5):
AttributeError: 'datetime.timedelta' object has no attribute 'minutes'

What am I doing wrong.?
What is the good way to check?
Please give a good example
Help is apriciated

Re: compare times

Posted: Tue May 05, 2015 3:15 pm
by elParaguayo
I think timedelta objects only store days, seconds and microseconds.

So:

Code: Select all

from datetime import datetime
s1 = '21:07'
s2 = '21:16'
delta = datetime.strptime(s2, '%H:%M') - datetime.strptime(s1, '%H:%M')
if (delta.total_seconds  > 300):
  print ">  5 minuten"

Re: compare times

Posted: Tue May 05, 2015 3:22 pm
by Canedje
elParaguayo wrote:I think timedelta objects only store days, seconds and microseconds.

So:

Code: Select all

from datetime import datetime
s1 = '21:07'
s2 = '21:16'
delta = datetime.strptime(s2, '%H:%M') - datetime.strptime(s1, '%H:%M')
if (delta.total_seconds  > 300):
  print ">  5 minuten"

Thanks for the swift answer.
No error indeed.
But 300 is not 5 minutes it Always give true now.
How to calculate 5 minutes in microseconds?

EDIT:
I found the solution. The correct code has to be without "total":

Code: Select all

from datetime import datetime
s1 = '21:07'
s2 = '21:13'
delta = datetime.strptime(s2, '%H:%M') - datetime.strptime(s1, '%H:%M')
print delta.seconds
if (delta.seconds  > 300):
  print ">  5 minuten"

Re: compare times

Posted: Tue May 05, 2015 3:32 pm
by elParaguayo
Can you give an example where the 5 minutes is not working? Your example code is an interval of 9 minutes.

May be my fault. I think "total_seconds" is a method so would need to be terminated with "()" or you can just use "delta.seconds"

EDIT: Ah - looks like you've found the issue already and it was my fault as I said!

Re: compare times

Posted: Tue May 05, 2015 4:09 pm
by Canedje
elParaguayo wrote:Can you give an example where the 5 minutes is not working? Your example code is an interval of 9 minutes.

May be my fault. I think "total_seconds" is a method so would need to be terminated with "()" or you can just use "delta.seconds"

EDIT: Ah - looks like you've found the issue already and it was my fault as I said!
Thanks anyway.
You gave me the right direction :D