I have a start date and an end date and I'd like to know how many months that occurrence fell in. For example if my start date was 2009, 01, 31 and the end date was 2009, 02, 01 I'd like to calculate that the occurrence fell in 2 different months. I've been playing around with datetime and dateutil but I can't seem to come up with anything. Could anyone point me in the right direction?

Dani AI

Generated

A short clarification and a safer implementation for counting distinct calendar months touched by a date range.

your arithmetic approach is a common, compact way to get an inclusive "months touched" count, and s quick check is right for many cases. The main things to decide up front are (a) do you mean calendar months touched (Jan and Feb count if the range crosses month boundary) or full months elapsed, and (b) should the end be inclusive. Once those are defined you want to guard against datetime vs date objects, swapped inputs, and odd month rolls (end-of-month, leap day).

A simple, robust function (pure stdlib) that counts distinct month/year pairs by stepping month-by-month:

import datetime

def months_touched(start, end):
    if isinstance(start, datetime.datetime):
        start = start.date()
    if isinstance(end, datetime.datetime):
        end = end.date()
    if start > end:
        start, end = end, start
    count = 0
    cur = start.replace(day=1)
    last = end.replace(day=1)
    while cur <= last:
        count += 1
        if cur.month == 12:
            cur = datetime.date(cur.year + 1, 1, 1)
        else:
            cur = datetime.date(cur.year, cur.month + 1, 1)
    return count

Troubleshooting notes: convert datetimes to dates to avoid time-of-day surprises; explicitly define inclusive/exclusive semantics; for large spans this loop is fine (one iteration per month). If you prefer a library helper, see the stdlib datetime docs (datetime — Basic date and time types) or use dateutil.relativedelta for month arithmetic (relativedelta docs).

I think this pretty well does the trick. Anyone spot any pitfalls?

import datetime

startdate = datetime.date(2008,01,01)
enddate = datetime.date(2009,01,02)

y = (enddate.year - startdate.year) * 12
m = ((enddate.month - startdate.month) + y) + 1

print "Months =", str(m)

i think this works fine and i tried it removing str before (m) and it worked to so i can say its good do you have any question?

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.