Is it possible to compare day + month(not year) against current day + month in Python?

Question:

I’m getting data in the format of ‘May 10’ and I am trying to figure out if it’s for this year or next. The date is for only a year so May 10 would mean May 10 2015 while May 20 would be May 20 2014.

To do this, I wanted to convert the string into a date format and compare but without the year I’m getting this error:

ValueError: unconverted data remains:

Here’s a rough idea of my current approach:

if datetime.strptime(DATE_TO_COMPARE, '%b %d')  >  time.strftime("%d %m"): #need to figure out may 11 is for this year or next year. Year is not provided.
    print datetime.strptime(DATE_TO_COMPARE, '%b %d'), ' > ',  time.strftime("%d %m")

Is there a better way to do it? I’m thinking of making a dictionary of months and then converting the month into a number then adding it the day (i.e.Dec 5 = 512) and comparing it. But not sure if there’s a better way?

Asked By: Lostsoul

||

Answers:

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:
    # last year
    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
Answered By: Martijn Pieters
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)
Answered By: user14835532
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.