Home > OS >  Get the first week Monday of the previous month
Get the first week Monday of the previous month

Time:03-30

I'm trying to display the first week Monday of the previous month. For an example for Feb 2022, I wish to get 31-1-2022 as the first Monday.

from datetime import datetime, date, timedelta

previous_month = date.today().replace(day=1) - timedelta(days=1)

date = datetime.strptime(str(previous_month), "%Y-%m-%d")

year= date.year
month = date.month

d = datetime(year, int(month),7)
offset = -d.weekday()
first_monday = d   timedelta(offset)

print(first_monday)

However the code above, display it as 7-2-2022.

CodePudding user response:

Find the 1st day of the month. Use its weekday number and subtract it:

>>> from datetime import *
>>> last = date.today().replace(day=1) - timedelta(days=1)
>>> last
datetime.date(2022, 2, 28)  # last day of last month
>>> first = last.replace(day=1)
>>> first
datetime.date(2022, 2, 1)  # first day of last month
>>> first.weekday()
1  # Tuesday
>>> first - timedelta(days=first.weekday())
datetime.date(2022, 1, 31)  # Monday of first week of last month

Note that "the first week" has many competing possible definitions. This merely finds the Monday of the week in which the 1st of last month is situated. Whether this is what you want and whether that corresponds to any standard is a different topic.

CodePudding user response:

from datetime import datetime, date, timedelta
previous_month = date.today().replace(day=1) - timedelta(days=1)
year= previous_month.year
month = previous_month.month

offset = previous_month.replace(day=1).weekday()
print(datetime(year,month,1) - timedelta(days=offset))

if monday, the weekday is 0 so you can substract from the first day of any month to find first monday.

CodePudding user response:

This indeed is not trivial. Especially as the first Monday could jump to even one month earlier. But we can get the isocalendar week a date is in. So we need to:

  1. Get the first day of last month
  2. Get the calendar week from that day
  3. Get the first day of that calendar week

1. first step - geht the first

last_month = date.today().month - 1
first_day_lm = date.today().replace(day=1, month=last_month)

2. The calendar week

week = first_day_lm.isocalendar()

3. The first day of the isocalendar

first_monday = datetime.strptime(
    f"{week.year}_{week.week}_1", 
    "%G_%V_%u"
)

Result should be: datetime.datetime(2022, 1, 31, 0, 0)

  • Related