views:

149

answers:

2

Hello,

I have a datetime.datetime property var. I would like to know if it is less than one hour of the current time. Something like

var.hour<datetime.datetime.today().hour - 1

Problem with the above syntax is that

datetime.datetime.today().hour

returns a number such as "10" and it is not really a date comparation but more of a numbers comparation.

What is the correct syntax?

Thanks!

Joel

+3  A: 

Use datetime.timedelta.

var < datetime.datetime.today() - datetime.timedelta(hours=1)
Daniel Roseman
That should bevar < datetime.datetime.today() - datetime.timedelta(hours=1)without the var.HOUR, right?:)
Joel
Ah yes you're right, thanks. Fixed.
Daniel Roseman
that's correct. datetime.hour is an int and not something that can be compared with datetime objects
whaley
Since you only need to get the difference in hours, this one is good enough. dateutil.relativedelta gives you more: years, months etc.
pocoa
A: 

You can use dateutil.relativedelta

from datetime import datetime, timedelta
from dateutil.relativedelta import relativedelta

now = datetime.now()
other_time = now + timedelta(hours=8)
diff = relativedelta(other_time, now)
print diff.hours # 8
pocoa