This question already has answers here:
Return datetime object of previous month
(23 answers)
Closed 6 years ago.
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.
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 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)
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
)
Related
This question already has answers here:
How to get the last day of the month?
(44 answers)
Closed last month.
There is a date like this:
Timestamp('2020-10-17 00:00:00')
How can I get the end of next month?
The output should be like this:
Timestamp('2020-11-30 00:00:00')
I tried rrule but it does not work correctly.
My code:
import pandas as pd
from datetime import date
from dateutil.rrule import rrule, MONTHLY
start_date = date(2020, 9, 17)
end_date = date(2020, 10, 31)
for d in rrule(MONTHLY, dtstart=start_date, until=end_date):
t = pd.Timestamp(d)
print(t)
The output:
2020-09-17 00:00:00
2020-10-17 00:00:00
I am going to get end of month.
in my case, change first day of next 2 month.
and then minus 1 day.
i also use this in java.
sample code
import pandas as pd
t = pd.Timestamp('2020-10-17 00:00:00')
t = t.replace(day=1)
answer = t + pd.DateOffset(months=2) + pd.DateOffset(days=-1)
In addition to the other's answers, you can also use calender module to get the last day of next month, as follows:
import pandas as pd
from datetime import date
import calendar
def get_nextmonth(d):
nextmonth_lastday = calendar.monthrange(d.year, d.month+1)[1] # this return first and last day of the given month, such as (0, 30)
return date(d.year, d.month+1, nextmonth_lastday)
start_date = date(2020, 9, 17)
print(get_nextmonth(start_date))
# 2020-10-31
Dateutil also works:
I set the days to 1, go two months further, and go one day back.
#pip install python-dateutil
from datetime import date
from dateutil.relativedelta import relativedelta
DAY = relativedelta(days=+1)
MONTH = relativedelta(months=+1)
first_date = date(2020, 10, 17).replace(day=1)
print(first_date + 2 * MONTH - DAY)
Output:
2020-11-30
Use pandas vectored way which is fast for large amounts of data.
import pandas as pd
ts = pd.Timestamp(2022, 1, 15)
ts + pd.offsets.DateOffset(months=1) + pd.offsets.MonthEnd(0) -->
Out: Timestamp('2022-02-28 00:00:00')
ts = pd.Timestamp(2022, 1, 31)
ts + pd.offsets.DateOffset(months=1) + pd.offsets.MonthEnd(0) --> putting 0 to get same month last date though it was last date
Out: Timestamp('2022-02-28 00:00:00')
ts = pd.Timestamp(2022, 1, 31)
ts + pd.offsets.DateOffset(months=1) + pd.offsets.MonthEnd()
Out: Timestamp('2022-03-31 00:00:00')
With beautiful-date, you could do:
from beautiful_date import D, months, day, days
last_day_of_the_month = D.today() + 1 * months + 1 * day - 1 * days
This takes the current day (D.today()), goes to the next month (+ 1 * months), goes to the first day of the next month (+ 1 * day), and goes one day back, i.e. last day of the current month (- 1 * days)
And you can easily convert it to datetime:
last_day_of_the_month[0:0]
I would do like this:
from datetime import date,timedelta
start_date = date(2020, 9, 17)
last_day_month=date(start_date.year,start_date.month+1,1)-timedelta(days=1)
You could do it like this:
import pandas as pd
from datetime import datetime, date
date = date(2020, 10, 17)
last_day_of_next_month = pd.Timestamp(datetime.datetime(date.year, ((date.month+2) % 12), 1) - datetime.timedelta(days=1))
Basically, this just created a new date at the first day of the month after next and subtracts one day to get the last day of the next month.
EDIT:
This can be done more cleanly by using pandas DateOffsets as mentioned in the comments and by another answer:
import pandas as pd
from datetime import date
date = date(2020, 10, 17)
last_day_of_next_month = pd.Timestamp(date) + pd.offsets.DateOffset(months=1) + pd.offsets.MonthEnd(0)
I'm trying to find the difference in months between two dates using relativedelta. I'm able to find the difference in years and days but I get 0 when I filter on months. Any suggestions?
from dateutil import relativedelta as rd
import datetime as date
dateformat = '%Y/%m/%d'
startDate = date.strptime('2017/07/01',dateformat).date()
endDate = date.strptime('2019/10/29',dateformat).date()
date_diff = rd.relativedelta(endDate,startDate)
print(date_diff.days)
relativedelta shows the difference as years, months, and days. It's not going to show net months if that's what you're looking for. If two dates happen to be on the same month in different years the months attribute will be zero.
If you want to show the total months, you can write a small function that does that for you by adding in the years value.
from datetime import datetime
from dateutil.relativedelta import relativedelta
def month_delta(start_date, end_date):
delta = relativedelta(end_date, start_date)
# >>> relativedelta(years=+2, months=+3, days=+28)
return 12 * delta.years + delta.months
d1 = datetime(2017, 7, 1)
d2 = datetime(2019, 10, 29)
total_months = month_delta(d1, d2)
print(total_months)
# >>> 27
Here's the solution:
from datetime import datetime
def diff_month(d1, d2):
return (d1.year - d2.year) * 12 + d1.month - d2.month
assert diff_month(datetime(2010,10,1), datetime(2010,9,1)) == 1
assert diff_month(datetime(2010,10,1), datetime(2009,10,1)) == 12
end-start will produce timedelta object on which days attribute will gve the required days difference
>>> from datetime import date
>>> start = date(2017,7,1)
>>> end = date(2017,11,11)
>>> (end-start).days
133
So this code what I want:
import datetime
d = datetime.date.today()
three_months_ago = d - timedelta(months=3)
However, as we know, the 'months' param does not exist in timedelta.
I admit I can program like this to achieve the goal:
if d.month > 3:
three_months_ago = datetime.date(d.year, d.month-3, d.day)
else:
three_months_ago = datetime.date(d.year-1, d.month-3+12, d.day)
But this seems really stupid...
Can you guys tell me how to realize this smartly?
This could help:
>>>from dateutil.relativedelta import relativedelta
>>>import datetime
>>>datetime.date.today()
datetime.date(2016, 3, 10)
>>>datetime.date.today() - relativedelta(months=3)
datetime.date(2015, 12, 10)
You can use relativedelta() to add or subtract weeks and years too.
Numpy's timedelta has months support, ie:
np.timedelta64(3, 'M')
This question already has answers here:
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 7 years ago.
I have a raw input from the user such as "2015-01-30"...for the query I am using, the date has to be inputed as a string as such "yyyy-mm-dd".
I would like to increment the date by 1 month at end of my loop s.t "2015-01-30" becomes "2015-02-27" (ideally the last business day of the next month). I was hoping someone could help me; I am using PYTHON, the reason I want to convert to datetime is I found a function to add 1 month.
Ideally my two questions to be answered are (in Python):
1) how to convert string "yyyy-mm-dd" into a python datetime and convert back into string after applying a timedelta function
2) AND/or how to add 1 month to string "yyyy-mm-dd"
Maybe these examples will help you get an idea:
from dateutil.relativedelta import relativedelta
import datetime
date1 = datetime.datetime.strptime("2015-01-30", "%Y-%m-%d").strftime("%d-%m-%Y")
print(date1)
today = datetime.date.today()
print(today)
addMonths = relativedelta(months=3)
future = today + addMonths
print(future)
If you import datetime it will give you more options in managing date and time variables. In my example above I have some example code that will show you how it works.
It is also very usefull if you would for example would like to add a x number of days, months or years to a certain date.
Edit:
To answer you question below this post I would suggest you to look at "calendar"
For example:
import calendar
january2012 = calendar.monthrange(2002,1)
print(january2012)
february2008 = calendar.monthrange(2008,2)
print(february2008)
This return you the first workday of the month, and the number of days of the month.
With that you can calculate what was the last workday of the month.
Here is more information about it: Link
Also have a loook here, looks what you might could use: Link
converting string 'yyyy-mm-dd' into datetime/date python
from datetime import date
date_string = '2015-01-30'
now = date(*map(int, date_string.split('-')))
# or now = datetime.strptime(date_string, '%Y-%m-%d').date()
the last business day of the next month
from datetime import timedelta
DAY = timedelta(1)
last_bday = (now.replace(day=1) + 2*31*DAY).replace(day=1) - DAY
while last_bday.weekday() > 4: # Sat, Sun
last_bday -= DAY
print(last_bday)
# -> 2015-02-27
It doesn't take into account holidays.
You can use a one-liner, that takes the datetime, adds a month (using a defined function), and converts back to a string:
x = add_months(datetime.datetime(*[int(item) for item in x.split('-')]), 1).strftime("%Y-%m-%d")
>>> import datetime, calendar
>>> x = "2015-01-30"
>>> x = add_months(datetime.datetime(*[int(item) for item in x.split('-')]), 1).strftime("%Y-%m-%d")
>>> x
'2015-02-28'
>>>
add_months:
def add_months(sourcedate,months):
month = sourcedate.month - 1 + months
year = sourcedate.year + month / 12
month = month % 12 + 1
day = min(sourcedate.day,calendar.monthrange(year,month)[1])
return datetime.date(year,month,day)
To convert a string of that format into a Python date object:
In [1]: import datetime
In [2]: t = "2015-01-30"
In [3]: d = datetime.date(*(int(s) for s in t.split('-')))
In [4]: d
Out[4]: datetime.date(2015, 1, 30)
To move forward to the last day of next month:
In [4]: d
Out[4]: datetime.date(2015, 1, 30)
In [5]: new_month = (d.month + 1) if d.month != 12 else 1
In [6]: new_year = d.year if d.month != 12 else d.year + 1
In [7]: import calendar
In [8]: new_day = calendar.monthrange(new_year, new_month)[1]
In [9]: d = d.replace(year=new_year,month=new_month,day=new_day)
In [10]: d
Out[10]: datetime.date(2015, 2, 28)
And this datetime.date object can be easily converted to a 'YYYY-MM-DD' string:
In [11]: str(d)
Out[11]: '2015-02-28'
EDIT:
To get the last business day (i.e. Monday-Friday) of the month:
In [8]: new_day = calendar.monthrange(new_year, new_month)[1]
In [9]: d = d.replace(year=new_year,month=new_month,day=new_day)
In [10]: day_of_the_week = d.isoweekday()
In [11]: if day_of_the_week > 5:
....: adj_new_day = new_day - (day_of_the_week - 5)
....: d = d.replace(day=adj_new_day)
....:
In [11]: d
Out[11]: datetime.date(2015, 2, 27)
I am trying to get the date delta by subtracting today's date from the nth day of the next month.
delta = nth_of_next_month - todays_date
print delta.days
How do you get the date object for the 1st (or 2nd, 3rd.. nth) day of the next month. I tried taking the month number from the date object and increasing it by 1. Which is obviously a dumb idea because 12 + 1 = 13. I also tried adding one month to today and tried to get to the first of the month. I am sure that there is a much more efficient way of doing this.
The dateutil library is useful for this:
from dateutil.relativedelta import relativedelta
from datetime import datetime
# Where day is the day you want in the following month
dt = datetime.now() + relativedelta(months=1, day=20)
This should be straightforward unless I'm missing something in your question:
import datetime
now = datetime.datetime.now()
nth_day = 5
next_month = now.month + 1 if now.month < 12 else 1 # February
year = now.year if now.month < 12 else now.year+1
nth_of_next_month = datetime.datetime(year, next_month, nth_day)
print(nth_of_next_month)
Result:
2014-02-05 00:00:00
Using dateutil as suggested in another answer is a much better idea than this, though.
Another alternative is to use delorean library:
Delorean is a library that provides easy and convenient datetime
conversions in Python.
>>> from delorean import Delorean
>>> d = Delorean()
>>> d.next_month()
Delorean(datetime=2014-02-15 18:51:14.325350+00:00, timezone=UTC)
>>> d.next_month().next_day(2)
Delorean(datetime=2014-02-17 18:51:14.325350+00:00, timezone=UTC)
My approach to calculating the next month without external libraries:
def nth_day_of_next_month(dt, n):
return dt.replace(
year=dt.year + (dt.month // 12), # +1 for december, +0 otherwise
month=(dt.month % 12) + 1, # december becomes january
day=n)
This works for both datetime.datetime() and datetime.date() objects.
Demo:
>>> import datetime
>>> def nth_day_of_next_month(dt, n):
... return dt.replace(year=dt.year + (dt.month // 12), month=(dt.month % 12) + 1, day=n)
...
>>> nth_day_of_next_month(datetime.datetime.now(), 4)
datetime.datetime(2014, 2, 4, 19, 20, 51, 177860)
>>> nth_day_of_next_month(datetime.date.today(), 18)
datetime.date(2014, 2, 18)
Without using any external library, this can be achived as follows
from datetime import datetime, timedelta
def nth_day_of_next_month(n):
today = datetime.now()
next_month_dt = today + timedelta(days=32-today.day)
return next_month_dt.replace(day=n)