massu1000
massu1000

Reputation: 229

How to get the first and last date of the month with Year and Month in python

In the below code , from the month and year, need 1st and last date of the month

for ex month =3 and year= 2022

first_date = 2021-03-01 00:00:00

last_date = 2021-03-31 00:00:00

I tried with calendar but it simply returns (1 ,31)

import calendar

month =3
year= 2022
print( calendar.monthrange(2002, 1))

Upvotes: 2

Views: 11199

Answers (4)

Shlomo Gordon
Shlomo Gordon

Reputation: 1

You can use the dateutil library to accomplish this as well.

from dateutil.relativedelta import relativedelta

month = 3
year = 2022
first = date(year, month, 1)
last = first + relativedelta(day=31)

Upvotes: 0

Tal Folkman
Tal Folkman

Reputation: 2581

you can do it using datetime module

import datetime

def get_last_day_of_month(day):
    next_month = day.replace(day=28) + datetime.timedelta(days=4)
    return next_month - datetime.timedelta(days=next_month.day)

the output will be:

for month in range(1, 13):
    print(get_last_day_of_month(datetime.date(2020, month, 1)))

    
2020-01-31
2020-02-29
2020-03-31
2020-04-30
2020-05-31
2020-06-30
2020-07-31
2020-08-31
2020-09-30
2020-10-31
2020-11-30
2020-12-31

for the first day you can just put the day always 1

Upvotes: 1

AJITH
AJITH

Reputation: 1175

From monthrange() you will get the first day and the number of days in that month. You can use the datetime method to convert it to date.

month =3
year= 2022
first, last = calendar.monthrange(year, month)
print(first, last)

print(datetime.datetime(year, month, 1))
print(datetime.datetime(year, month, last))

Upvotes: 7

corvusMidnight
corvusMidnight

Reputation: 648

You could write your own function to calculate the last day of the month:

def last_day_of_month(date):
    if date.month == 12:
        return date.replace(day=31)
    return date.replace(month=date.month+1, day=1) - datetime.timedelta(days=1)

So:

>>> last_day_of_month(datetime.date(2021, 3, 19))
datetime.date(2021, 3, 31)

Similarly, we can use a one-liner for the first date:

(dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)

So:

dt = datetime.datetime(2021, 3, 19)
print((dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1))
>>> 2021-03-01 00:00:00

Upvotes: 1

Related Questions