Facebook Twitter Instagram
    Facebook Twitter Instagram Pinterest Vimeo
    Hand On CodeHand On Code
    Hand On CodeHand On Code
    Home»python»Python Get First Day Of Month
    python

    Python Get First Day Of Month

    March 29, 2023No Comments7 Mins Read
    Share
    Facebook Twitter LinkedIn Pinterest Email

    The First Day Of The Month Is Given To Python.

    When working with a datetime in Python, you will almost certainly want a method for locating the first day of the month. This Python lesson may be used as a teaching tool, and it will take you step by step through the process of writing that assignment.

    You are going to learn some Python in this lesson.

    :

    • How to get the

      first day

      of the month (start date)
    • How to get the first day of

      next

      month and the

      previous

      month

    Furthermore, check How to Obtain the Final Day of the Month in Python.

    .

    Table of contents


    • How To Find The First Day Of The Month In Python


      • Example 1: Get the first day of the month using the replace() method

      • Example 2: Get the first day of the month using the timedelta class

    • Get The First Day Of Next Month In Python


      • Example: Get The First Day Of Next Month

    • Get The First Day Of Previous Month In Python


      • Example: Get The First Day Of the Previous Month

    How To Find The First Day Of The Month In Python

    Let’s say your application gets a datetime object, and you want to transform the date received to the first day of the month. How would you go about doing this? For instance, the current date and time is ” 2022-9-14 “, and you want to create some code that would give you back ” 2022-9-1 “, which is the first day of the month or the beginning date of a month. The steps that are shown below demonstrate how to utilise the datetime. Using the replace() function to locate the date and time that corresponds to the first day of a month

    object.


    1. Import datetime class from a datetime module


      Python datetime

      module provides various functions to create and manipulate the date and time. Use the

      from datetime import datetime

      statement to import a

      datetime

      class from a datetime module.


    2. Store datetime object in a variable

      Store the input datetime object in a variable for further processing. Or you can use the

      datetime.today()

      to

      get the current datetime

      if you want to find the start date of a current month.


    3. Use the datetime.replace() method

      The


      datetime.replace()


      function

      replaces the DateTime object’s contents with the given parameters

      . This method has various parameters, but here we will use the


      day


      parameter because we want to replace the day number of a datetime object with the 1 (first day of the month).

      For example,

      datetime(2022, 8, 27).replace(day=1)

      will return

      datetime(2022, 8, 1) i.e., nothing but the

      first day of a month or a start date of a month.

    Example 1: Get the first day of the month using the replace() method

    from datetime import datetime
    # get today's datetime
    input_dt = datetime.today()
    print('Datetime is:', input_dt)
    res = input_dt.replace(day=1)
    print('First day of a month:', res)
    # print only date
    print('Only date:', res.date())

    Run Output

    :

    Datetime is: 2022-09-15 15:43:55.304669
    First day of a month: 2022-09-01 15:43:55.304669
    Only date: 2022-09-01

    Example 2: Get the first day of the month using the timedelta class

    Using the timedelta class that is included in a datetime module will provide the same results as before.

    The length that is represented by the difference in either dates, times, or datetime occurrences between two points in time is referred to as a timedelta. The resolution of a timedelta is in microseconds. We are able to modify the value of a given DateTime by adding or removing weeks, days, hours, minutes, seconds, microseconds, and milliseconds by using the timedelta.

    Find the first day of the month based on a given date by using the day parameter of a timedelta class. This will allow you to replace the day number of a datetime object with the number 1, which represents the first day of the month. Follow each of the instructions below.

    :

    • First, import the datetime and timedelta class from a datetime module.
    • Next, get the actual day number of an input datetime object using the

      strftime()

      method. For example, if datetime is ‘2022-8-24′, it will return ’24’.
    • Next, use the

      timedelta

      class to subtract the actual day – 1 from an input date to get the first day of the month (starting date of a month)

    Example

    :

    from datetime import datetime, timedelta
    input_dt = datetime.today().date()
    print('Input date:', input_dt)
    # get the actual day number
    day_num = input_dt.strftime("%d")
    # subtract those number of days from input date
    # using the timedelta
    res = input_dt - timedelta(days=int(day_num) - 1)
    print('First day of month:', res)

    Run Output

    :

    Input date: 2022-09-15
    First day of month: 2022-09-01

    Furthermore, check How to Obtain the Final Day of the Month in Python.

    .

    Get The First Day Of Next Month In Python

    Let’s look at some Python code to determine how to obtain the beginning date of the next month. For instance, if datetime includes the 17th of August 2022, the first day of the next month is going to be the 1st of September 2022. Also, the first day of the next month is going to be 2022-01-01 if the datetime is “2021-12-31.”

    We are able to get the start day of the next month by using the timedelta class that is included inside a DateTime module. Follow each of the instructions below.

    .

    • Import datetime and timedelta class from datetime module
    • Replace the day number of a datetime to 1 using the

      datetime.replace()

      method
    • Next, pick a number that certainly is more than any month but less than any two months combined and add them to input datetime using timedelta
    • Next, again replace the day number of an input datetime to 1 using the

      datetime.replace()

      method

    Example: Get The First Day Of Next Month

    from datetime import datetime, timedelta
    input_dt = datetime(2022, 8, 26)
    print('Input date:', input_dt.date())
    # first replace day number with 1
    input_dt = input_dt.replace(day=1)
    # add 32 days to the input datetime
    input_dt = input_dt + timedelta(days=32)
    # replace day number with 1
    res = input_dt.replace(day=1)
    print('First day of month:', res.date())

    Run Output

    :

    Input date: 2022-08-26
    First day of month: 2022-09-01

    The approach shown above is applicable in every circumstance. Check out the example down below. Example

    :

    from datetime import datetime, timedelta
    input_dt = datetime(2021, 12, 31)
    print((input_dt.replace(day=1) + timedelta(days=32)).replace(day=1))
    input_dt = datetime(2020, 2, 29)
    print((input_dt.replace(day=1) + timedelta(days=32)).replace(day=1))
    input_dt = datetime(2022, 12, 1)
    print((input_dt.replace(day=1) + timedelta(days=32)).replace(day=1))

    Run Output

    :

    2022-01-01 00:00:00
    2020-03-01 00:00:00
    2023-01-01 00:00:00

    Get The First Day Of Previous Month In Python

    Let’s look at how to use Python to get the first day of the month that just passed. As an instance, if datetime displays the date 2022-08-17, the first day of the month before that would be 2022-07-01. In addition, if the datetime is ‘2022-1-1,’ the first day of the month before that would be December 1, 2021.

    We are able to get the beginning day of the previous month by using the timedelta class that is included inside a DateTime module.

    Use the following:

    steps.

    • Import datetime and timedelta class from datetime module
    • Replace the day number of an input datetime to 1 using the

      datetime.replace(day=1)

      method
    • Use timedelta to backup a single day to the last day of the previous month.
    • Next, pick a number that certainly is more than any month but less than any two months combined and add them to input datetime using timedelta
    • Next, again replace the day number of an input datetime to 1 using the

      datetime.replace(day=1)

      method

    Example: Get The First Day Of the Previous Month

    from datetime import datetime, timedelta
    input_dt = datetime(2021, 12, 31)
    print('Input datetime:', input_dt.date())
    # first replace day number with 1
    dt = input_dt.replace(day=1)
    # subtract 1 day from input datetime
    # go back to previous month i.e. last date of previous month
    dt = dt - timedelta(days=1)
    # replace day number with 1
    res = dt.replace(day=1)
    print('first day of a previous month:', res.date())

    Run Output

    :

    Input datetime: 2021-12-31
    first day of a previous month: 2021-11-01
    Learn Python free Python Code Python Course Free download python coursefree Courses Download Python Get First Day Of Month Python Language
    Share. Facebook Twitter Pinterest LinkedIn Tumblr Email
    Previous ArticleGmail API in Python
    Next Article Kickstarting a Django Open Source Project

    Related Posts

    python

    Class method vs Static method in Python

    April 7, 2023
    python

    Python Program to Count the Number of Matching Characters in a Pair of String

    April 7, 2023
    python

    Coroutine in Python

    April 7, 2023
    Add A Comment

    Leave A Reply Cancel Reply

    Facebook Twitter Instagram Pinterest
    © 2023 ThemeSphere. Designed by ThemeSphere.

    Type above and press Enter to search. Press Esc to cancel.