Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract a month from a date in Python? [duplicate]

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.

like image 821
ldevyataykina Avatar asked Jul 05 '16 10:07

ldevyataykina


3 Answers

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)
like image 116
Rahul K P Avatar answered Oct 20 '22 06:10

Rahul K P


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)
like image 7
mitghi Avatar answered Oct 20 '22 05:10

mitghi


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
)
like image 4
JoseKilo Avatar answered Oct 20 '22 07:10

JoseKilo