Search code examples
pythondatedatetimepython-datetime

Determine larger month, ignoring the day


What function could I write in python to determine whether or not the date for f is bigger than t, ignoring the day component - which it obviously is?

t = datetime.date(2014, 12, 30)
f = datetime.date(2015, 1 ,2)

I tried the following:

if t.month > f.month:

However, this doesn't work as it doesn't take into account the year. I only want to use the year and month - not the days.

Please note that 't' may also be datetime.datetime(2015, 2, 2)


Solution

  • You could compare the dates with the day component set to 1:

    t.replace(day=1) < f.replace(day=1)
    

    or compare both the year and the month:

    if t.year < f.year or (t.year == f.year and t.month < f.month):
    

    The latter is easier tested with a tuple comparison:

    if (t.year, t.month) < (f.year, f.month):
    

    Demo:

    >>> from datetime import date
    >>> t = date(2015, 1, 2)
    >>> f = date(2015, 2, 2)
    >>> t.replace(day=1) < f.replace(day=1)
    True
    >>> t.year < f.year or (t.year == f.year and t.month < f.month)
    True
    >>> (t.year, t.month) < (f.year, f.month)
    True
    >>> t = date(2014, 12, 30)
    >>> f = date(2015, 1, 2)
    >>> t.replace(day=1) < f.replace(day=1)
    True
    >>> t.year < f.year or (t.year == f.year and t.month < f.month)
    True
    >>> (t.year, t.month) < (f.year, f.month)
    True