I need to get the first day of last month from any date.
I know that I can use monthdelta(datetime(2010,3,30), -1)
to get last month, but it doesn't return the first day.
Try like this. With using datetime
and datetutil
.
(if datetutil
not available for you install pip install python-dateutil
)
In [1]: from datetime import datetime
In [2]: import dateutil.relativedelta
In [3]: today_date = datetime.now().date()
In [4]: today_date
Out[1]: datetime.date(2016, 7, 5)
In [5]: last_month = today_date - dateutil.relativedelta.relativedelta(months=1)
In [6]: last_mont_first_date = last_month.replace(day=1)
In [7]: last_mont_first_date
Out[2]: datetime.date(2016, 6, 1)
Input:
datetime.date(2016, 7, 5)
Output
datetime.date(2016, 6, 1)
This can be done by first calculating the first day of current month ( or any given date ), then subtracting it with datetime.timedelta(days=1) which gives you the last day of previous month.
For demonstration, here is a sample code:
import datetime
def get_lastday(current):
_first_day = current.replace(day=1)
prev_month_lastday = _first_day - datetime.timedelta(days=1)
return prev_month_lastday.replace(day=1)
Try this :
from datetime import date
d = date.today()
d.replace(
year=d.year if d.month > 1 else d.year - 1,
month=d.month - 1 if d.month > 1 else 12,
day=1
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With