Evelyn
Evelyn

Reputation: 33

Generate dates for a particular month?

is there any way to generate all the dates of a particular month when the month and year are inputted?

I have

daterange = date_range(date1, date2)
dates=[]
for x in daterange:
    dates.append((x.strftime('%Y-%m-%d')))

using pandas, but how can I account for different month lengths?

Upvotes: 1

Views: 2422

Answers (4)

xnx
xnx

Reputation: 25518

I find I can't import calendar on my system, so here's a datetime-only solution:

from datetime import date, timedelta

month, year = 2, 2008

day = timedelta(days=1)
date1 = date(year, month, 1)
dates = []
d = date1
while d.month == month:
    dates.append(d)
    d += day

(Creates a list of the dates of days in February 2008, a leap year). If you want string representations of the dates, you can use:

from datetime import timedelta, datetime

month, year = 2, 2008

day = timedelta(days=1)
date1 = datetime(year, month, 1)
d = date1
dates = []
while d.month == month:
    dates.append(d.strftime('%Y-%m-%d'))
    d += day

Upvotes: 1

dhke
dhke

Reputation: 15388

The calendar module has all you need:

import calendar
first_weekday, month_days = calendar.monthrange(year, month)
for mday in xrange(1, month_days + 1):
    print mday

Upvotes: 0

Tim Henigan
Tim Henigan

Reputation: 62168

You can do that with the calendar module:

import calendar
date_of_first_weekday, number_days_in_month = calendar.monthrange(year, month)

Upvotes: 0

jwilner
jwilner

Reputation: 6606

You could use pd.offsets.MonthBegin and then use an end exclusive daily date range:

dts = pd.date_range(month_start, month_start + pd.offsets.MonthBegin(1), closed="left") 

Upvotes: 3

Related Questions