Reputation: 299
I have django app and problems with set correct conditions for dates:
Here are my filters:
Task 1
@register.filter(name='if_more_then_24')
def if_more_then_24(time):
return time + datetime.timedelta(hours=24) > timezone.now()
Task 2
@register.filter(name='if_less_then_24')
def if_less_then_24(time):
return time + datetime.timedelta(hours=24) < timezone.now()
Task 3
@register.filter(name='now_online')
def now_online(time):
return time < timezone.now()
@register.filter(name='not_online')
def not_online(time):
return time > timezone.now()
But code didn't work because when I have {{ object.event_from }} Dec. 11, 2016, 5:00 p.m. and today is Dec. 12, 2016, 4:31 p.m. Counter shows hours 1:28 instead days
Upvotes: 0
Views: 1956
Reputation: 4469
I think you may have your logic backward:
def if_more_then_24(time):
return time + datetime.timedelta(hours=24) > timezone.now()
If a given time
(say sometime yesterday) + 24 hours is greater than right now, that means that it was less then 24 hours ago (because adding 24 hours results in a time in the future).
def if_less_then_24(time):
return time + datetime.timedelta(hours=24) < timezone.now()
If a given time
+ 24 hours is less than right now, it means that time
was more than 24 hours ago, because adding a day still is in the past.
So, wherever you're calling your functions will be expecting the opposite result. Switch the <
and >
in these functions, and it should correct this.
See here for more on subtracting one day.
Upvotes: 2