Is It Possible To Compare Day + Month(not Year) Against Current Day + Month In Python?
I'm getting data in the format of 'May 10' and I am trying to figure out if its for this year or next. The date is for only a year so May 10 would mean May 10 2015 while May 20 wo
Solution 1:
Parse, then replace the year in the result (with date.replace()
and test against today, not a string:
from datetime import date, datetime
today = date.today()
parsed = datetime.strptime(DATE_TO_COMPARE, '%b %d').date().replace(year=today.year)
if parsed > today:
# lastyear
parsed = parsed.replace(year=today.year -1)
I used date
objects here as the time of day shouldn't figure in your comparisons.
Demo:
>>>from datetime import date, datetime>>>today = date.today()>>>DATE_TO_COMPARE = 'May 10'>>>parsed = datetime.strptime(DATE_TO_COMPARE, '%b %d').date().replace(year=today.year)>>>parsed
datetime.date(2014, 5, 10)
>>>parsed > today
False
>>>DATE_TO_COMPARE = 'May 20'>>>parsed = datetime.strptime(DATE_TO_COMPARE, '%b %d').date().replace(year=today.year)>>>parsed
datetime.date(2014, 5, 20)
>>>parsed > today
True
Solution 2:
from datetime import date, datetime
today = date.today()
print(today)
DATE_TO_COMPARE = 'Dec 16'
parsed = datetime.strptime(DATE_TO_COMPARE, '%b %d').date().replace(year=today.year)
print(parsed)
print(parsed == today)
Post a Comment for "Is It Possible To Compare Day + Month(not Year) Against Current Day + Month In Python?"