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.
if date in (start, end): print('in between') else: print('No! ') date, start and end are all variables with the format of 1/1.
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.
You can use equal to comparison operator = to check if one datetime object is has same value as other.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With