Sparky
Sparky

Reputation: 91

Getting a list of months between two dates

I need to implement the code which will help me to get the list of months between two dates.

I already have the code which will give the month delta , That is the number of months.

Actually, I need the way to achieve getting the list of months between two dates.

Here it is code for getting month delta.

import calendar
import datetime

def calculate_monthdelta(date1, date2):
    def is_last_day_of_the_month(date):
        days_in_month = calendar.monthrange(date.year, date.month)[1]
        return date.day == days_in_month
    imaginary_day_2 = 31 if is_last_day_of_the_month(date2) else date2.day
    monthdelta = (
        (date2.month - date1.month) +
        (date2.year - date1.year) * 12 +
        (-1 if date1.day > imaginary_day_2 else 0)
        )
    print monthdelta
    return monthdelta

date2 = datetime.datetime.today()
date1 = date2.replace(month=01)

calculate_monthdelta(date1, date2)

Now I need the way to get the list of months between the same.

Any help is appreciated If there is any way to get the list of months between two dates.

Note: Please suggest any idea (If available) apart from the code I have used here.

Upvotes: 4

Views: 7895

Answers (4)

Amir nazary
Amir nazary

Reputation: 695

You can use the datae_range function in pandas library.

import pandas as pd

months = pd.date_range(data1, date2, freq="MS").strftime("%Y-%m").tolist()

It will give you a list of all months with the selected format (here in "%Y-%m") in the range of date1 and date2 which looks like somewhat like this:

['2012-01', '2012-02', '2012-03', '2012-04', '2012-05']

If you want only the distinct months between date1 and date2, you can use datae_range function like this:

months = pd.date_range(date1, date2, freq="MS").strftime("%m").tolist()
months = list(dict.fromkeys(months))

And the output looks like this:

['01', '02', '03', '04', '05']

Upvotes: 0

cheng chen
cheng chen

Reputation: 489

try this

import datetime
import time
from dateutil.rrule import rrule, MONTHLY
months = [dt.strftime("%m") for dt in rrule(MONTHLY, dtstart=date1, until=date2)]
print months

Upvotes: 13

NNNN
NNNN

Reputation: 1

Change your print statement to:
print calendar.month_name[:monthdelta]

Upvotes: -1

TheLazyScripter
TheLazyScripter

Reputation: 2665

Because I don't know your desired output I can't format mine, but this returns an integer of the total number of months between two dates.

def calculate_monthdelta(date1, date2):
    print abs(date1.year - date2.year) * 12 + abs(date1.month - date2.month)

Upvotes: -1

Related Questions