I'd like to write a function that will idempotently output either True or False on alternate datetime days, starting from a non-specific date and going on indefinitely.
For example, passing a datetime representing October 1st might output True, then October 2nd will output False, then October 3rd True, and so on... It should be possible to pass any datetime into this function and always get the same result for that datetime.
It should look something like:
def date_check(date_to_check):
if [condition related to date_to_check]:
return True
else:
return False
I just can't figure out what the condition should be to always return True or False on alternating days.
I've considered calculating based on day of week but this isn't possible due to odd number of days in the week. I've considered calculating based on whether the day of the month is odd or not but this won't work as months containing 31 days will produce two odd numbered days in a row (31 and 1).
EDIT: I considered also calculating based on whether the day of the year is odd or not but again: day 365 and day 1 will produce the same value consecutively.
Is there any way to do this?
CodePudding user response:
To do this, we need a calendar representation that just counts days without regard to anything else — no weeks or months or years. Skimming the datetime
module docs, one possibility would appear to be the date.toordinal()
method. Then we check whether that number is odd or even in the usual way.
def date_check(date_to_check):
return date_to_check.toordinal() % 2 == 0
Notes:
- To invert the sequence, use
!=
instead of==
- In principle, you'll need to check whether this works for BC dates if you need that; in practice, the calendar hasn't been uniform for nearly that long (with days skipped and added over the centuries), so if you need it to work that far back, you'll have to do a lot more work.
CodePudding user response:
Maybe start with some BASE_DATE
and then check the number of days between that date and the input you pass -
import datetime as dt
def alt_true_false(date_to_check):
BASE_DATE = dt.date(2022, 10, 1)
if (date_to_check - BASE_DATE).days % 2:
return False
return True
Output
alt_true_false(dt.date(2022, 10, 2))
# False
alt_true_false(dt.date(2022, 10, 3))
# True
alt_true_false(dt.date(2027, 10, 3))
# True
alt_true_false(dt.date(2026, 10, 3))
# False