12

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.

NineWasps
  • 2,081
  • 8
  • 28
  • 45
  • 1
    Why not `datetime(2010, 3 - 1, 1)`? – jonrsharpe Jul 05 '16 at 10:06
  • Because I have a lot of date `2016-05-13 19:05:38, 2016-06-18 19:05:46, 2016-06-12 19:06:46, 2016-03-13 19:07:04, 2016-02-13 19:09:59, 2016-09-13 19:11:11 ` and to all date I want to get first day of last month – NineWasps Jul 05 '16 at 10:09

3 Answers3

8

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)
mitghi
  • 889
  • 7
  • 20
5

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)
Rahul K P
  • 15,740
  • 4
  • 35
  • 52
4

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
)
JoseKilo
  • 2,343
  • 1
  • 16
  • 28