0

I'm new to python and Django. I've been playing around with the Django polls tutorial and all is going well but I'm still getting used to the syntax.

What does this line read in plain English?

return now - datetime.timedelta(days=1) <= self.pub_date <= now

The part I'm having trouble with is the <= operator. I'm aware this usually means less than or equal to but I've never seen them being used in succession such as above.

user3398918
  • 71
  • 3
  • 10
  • 5
    return whether `pub_date` is between yesterday (24 hours ago) and now. – Willem Van Onsem May 07 '19 at 17:13
  • 1
    See also https://stackoverflow.com/questions/10040143/how-to-do-a-less-than-or-equal-to-filter-in-django-queryset and https://stackoverflow.com/questions/34743988/how-to-do-less-than-or-equal-to-and-greater-than-equal-to-in-django-filter/34744213. – TylerH May 07 '19 at 19:42

1 Answers1

6

In short: it checks if self.pub_date is between 24 hours before now and now.

Python allows operator chaining [Python-doc]. It means that if you write x <= y <= z, that is short for x <= y and y <= z, except that y is evaluated only once.

You thus can read this as:

return (now - datetime.timedelta(days=1)) <= self.pub_date and self.pub_date <= now

Now now is likely the current timestamp, so that means that now - datetime.timedelta(days=1) is 24 hours before now. So in short it checks if self.pub_date is between 24 hours before now and now (both inclusive). If that holds it returns True, otherwise it returns False.

Likely - although we can not check that - now is the current timestamp, so it means if self.pub_date is between yesterday (same time) and the current timestamp.

Willem Van Onsem
  • 443,496
  • 30
  • 428
  • 555