Smruti Sahoo
Smruti Sahoo

Reputation: 169

find start and end date of previous month from current date in python

I need to find the start and end date of the previous month from the current date.

If the current date is 03-Feb-2021

The start date should be 01-Jan-2021 and the end date should be 31-Jan-2021.

how to achieve this as each month have a different number of days? Do we have any function in datetime to achieve this?

Upvotes: 2

Views: 8511

Answers (3)

Harnoor Kaur
Harnoor Kaur

Reputation: 11

import datetime
from dateutil.relativedelta import relativedelta

# Get current date
today = datetime.date.today()

# Get first day of previous month
first_day = today.replace(day=1) - relativedelta(months=1)

# Get last day of previous month
last_day = today.replace(day=1) - datetime.timedelta(days=1)

# Format dates
start = first_day.strftime('%d-%b-%Y')
end = last_day.strftime('%d-%b-%Y')

# Print dates
print("Start date:", start)
print("End date:", end)

Upvotes: 1

superb rain
superb rain

Reputation: 5520

>>> from datetime import date, timedelta
>>> this_first = date.today().replace(day=1)
>>> prev_last = this_first - timedelta(days=1)
>>> prev_first = prev_last.replace(day=1)
>>> prev_first, prev_last
(datetime.date(2021, 1, 1), datetime.date(2021, 1, 31))

Format if/as needed.

Upvotes: 20

Rajat Tyagi
Rajat Tyagi

Reputation: 378

first date will always be the 1st

# month_date = (datetime.now() - timedelta(days=20))
month_date = datetime.now().replace(day= monthrange(month_date.year,month_date.month - 1)[1]).strftime("%Y/%m/%d")
start_date = month_date.strftime("%Y/%m/01")
end_date = month_date.replace(day= monthrange(month_date.year,month_date.month)[1]).strftime("%Y/%m/%d")

imports are

from datetime import datetime, timedelta
from calendar import monthrange

you can add one condition for january so it will take december. If have any problem with that just add comment I will add that too.

Upvotes: -3

Related Questions