Vba_Beg
Vba_Beg

Reputation: 523

How to check dates basing on year and month in Python

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,

Upvotes: 0

Views: 858

Answers (2)

Adam Smith
Adam Smith

Reputation: 54163

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)]

Upvotes: 1

Delgan
Delgan

Reputation: 19617

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.

Upvotes: 3

Related Questions