;

How to Get the First Day of the Month using a specific Date in Python


Tutorialsrack 29/03/2020 Programs Python

In this article, we will learn how to get the first day of the month using a date in python.

There are many ways to get or find the first day of the month using a specific date in python. Here is some example as follows:

Example 1: In this example, we use the date.replace() method of the DateTime module to replace the date part of the date object to 1.

Example 1
# Import DateTime
from datetime import datetime
 
given_date = datetime.today().date()
 
first_day_of_month = given_date.replace(day=1)
 
print("\nFirst day of month: ", first_day_of_month, "\n")
# Output ==> First day of month:  2020-03-01

Example 2: In this example, we use the timedetla of the DateTime module 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 of the month.

Example 2
#Import Module
from datetime import datetime, timedelta
 
given_date = datetime.today().date()
 
first_day_of_month = given_date - timedelta(days = int(given_date.strftime("%d"))-1)
 
print("\nFirst day of month: ", first_day_of_month, "\n")
# Output ==> First day of month:  2020-03-01

Example 3: In this example, we use the strftime() method to format the date object with the day part as 01, which returns the first day of the month.

Example 3
# Import Module
import time
from datetime import datetime
 
given_date = datetime.today().date()
 
first_day_of_month = given_date.strftime("%Y-%m-01")
 
print("\nFirst day of month: ", first_day_of_month, "\n")
#Output ==> First day of month:  2020-03-01

Example 4: In this example, we extract the 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.

Example 4
# 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

I hope this article will help you to understand how to get the first day of the month using a date in python.

Share your valuable feedback, please post your comment at the bottom of this article. Thank you!


Related Posts



Comments

Recent Posts
Tags