How To Find First Day Of The Month In Python?

How To Find First Day Of The Month In Python?

In this post, how to find the first day of the month from the given date. There is no straight forward way to get a month’s first day in Python. We have to apply some simple logic to get it. Here are a few of the methods.

Method 1:

from datetime import datetime
 
givendate = datetime.today().date()
 
first_day_of_month = givendate.replace(day=1)
 
print("\nFirst day of month: ", first_day_of_month, "\n")

2.

strftime() is used to format the date object with the daypart as 01, which returns the first day of the month.

import time
from datetime import datetime
 
givendate = datetime.today().date()
 
first_day_of_month = givendate.strftime("%Y-%m-01")
 
print("\nFirst day of month: ", first_day_of_month, "\n")

3.

the time delta of the DateTime module is used to find the days from the first day to the given date and then subtract it from the given date to get the first day.

from datetime import datetime, timedelta
 
givendate = datetime.today().date()
 
first_day_of_month = givendate - timedelta(days = int(given_date.strftime("%d"))-1)
 
print("\nFirst day of month: ", first_day_of_month, "\n")

4.

Date Part such as year and month from the given Date and create a date using this date part to get the first day of the month and I think this is the easiest way to get the first day of the month of a specific date.

# Import Module
import datetime
def first_day_of_month(date):
    first_day = datetime.datetime(date.year, date.month, 1)
    return first_day.strftime('%Y-%m-%d')

print("\nFirst Day of Month: ", first_day_of_month(datetime.date(2020, 2, 25)))
#Output ==> First Day of Month:  2020-02-01

 

 

2021-10-03