Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking date against date range in Python

I have a date variable: 2011-01-15 and I would like to get a boolean back if said date is within 3 days from TODAY. Im not quite sure how to construct this in Python. Im only dealing with date, not datetime.

My working example is a "grace period". A user logs into my site and if the grace period is within 3 days of today, additional scripts, etc. are omitted for that user.

I know you can do some fancy/complex things in Python's date module(s) but Im not sure where to look.

like image 724
Ben Keating Avatar asked Jan 14 '11 20:01

Ben Keating


People also ask

How do you see if a date is between two dates in Python?

if date in (start, end): print('in between') else: print('No! ') date, start and end are all variables with the format of 1/1.

How do you iterate over a date range in Python?

Using pandas to Iterate through a range of dates We can use the date_range() function method that is available in pandas. It is used to return a fixed frequency DatetimeIndex.

How do I compare two date values in Python?

You can use equal to comparison operator = to check if one datetime object is has same value as other.


2 Answers

In Python to check a range you can use a <= x <= b:

>>> import datetime >>> today = datetime.date.today() >>> margin = datetime.timedelta(days = 3)  >>> today - margin <= datetime.date(2011, 1, 15) <= today + margin True 
like image 77
Mark Byers Avatar answered Oct 11 '22 21:10

Mark Byers


Subtracting two date objects gives you a timedelta object, which you can compare to other timedelta objects.

For example:

>>> from datetime import date, timedelta >>> date(2011, 1, 15) - date.today() datetime.timedelta(1) >>> date(2011, 1, 15) - date.today() < timedelta(days = 3) True >>> date(2011, 1, 18) - date.today() < timedelta(days = 3) False 

As to "where to look": the official documentation is excellent.

like image 44
Thomas Avatar answered Oct 11 '22 20:10

Thomas