0

I'd like to check the days for a given month . For an instance, if I input year 2017 and month 2 or February , I would like to receive all dates for that month, in this case 01-28.02.2017.

Is it possible to do in Python? Was trying to find something using google, but unsuccessfully.

Thanks in advance,

Vba_Beg
  • 453
  • 1
  • 6
  • 13
  • Possible duplicate of [Get Last Day of the Month in Python](https://stackoverflow.com/questions/42950/get-last-day-of-the-month-in-python) – bgfvdu3w Oct 08 '17 at 08:35
  • I am not looking for last day of month but for all days – Vba_Beg Oct 08 '17 at 08:38
  • 2
    Every month starts with day 1. If you know the first day and the last, then you also know everything between. – bgfvdu3w Oct 08 '17 at 08:39

2 Answers2

3

There is a function for this in the standard library: itermonthdates().

from calendar import Calendar

for date in Calendar().itermonthdates(2017, 2):
    print(date)

You may need to filter the dates with if date.month == 2, because it will contain days from the previous and next months if they belong to the same week.

Delgan
  • 18,571
  • 11
  • 90
  • 141
1

Alternative, as Mark suggested in the comments, if you know the month then you can do this yourself.

import calendar

year, month = 2017, 2

def days_in_month(date):
    if calendar.isleap(date.year) and date.month == 2:
        return 29
    else:
        return [None, 31, 28, 31, 30, 31, 30, ...][date.month]

date = datetime.date(year=year, month=month)

dates = [datetime.date(year=year, month=month, day=d) for d in range(1, days_in_month(date)+1)]
Adam Smith
  • 52,157
  • 12
  • 73
  • 112