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)
Related
I'm trying to convert this list of weeks in a year to dates in Python and then into a Pandas column but having weird results:
import datetime
from dateutil.relativedelta import relativedelta
week = [25,31]
year = 2021
dates = []
for i in week:
date = datetime.date(year, 1, 1) + relativedelta(weeks=+i)
dates.append(date)
print(dates)
The printout of the dates looks like this:
[datetime.date(2021, 6, 25), datetime.date(2021, 8, 6)]
i need it to look like this [ 2021-06-25, 2021-08-06]
Any ideas?
import datetime
from dateutil.relativedelta import relativedelta
dates = []
for i in week:
date = datetime.date(year, 1, 1) + relativedelta(weeks=+i)
dates.append(date)
df['date'] = pd.to_datetime(dates)
I need to find the start and end date of the previous month from the current date.
If the current date is 03-Feb-2021
The start date should be 01-Jan-2021 and the end date should be 31-Jan-2021.
how to achieve this as each month have a different number of days? Do we have any function in datetime to achieve this?
>>> from datetime import date, timedelta
>>> this_first = date.today().replace(day=1)
>>> prev_last = this_first - timedelta(days=1)
>>> prev_first = prev_last.replace(day=1)
>>> prev_first, prev_last
(datetime.date(2021, 1, 1), datetime.date(2021, 1, 31))
Format if/as needed.
first date will always be the 1st
# month_date = (datetime.now() - timedelta(days=20))
month_date = datetime.now().replace(day= monthrange(month_date.year,month_date.month - 1)[1]).strftime("%Y/%m/%d")
start_date = month_date.strftime("%Y/%m/01")
end_date = month_date.replace(day= monthrange(month_date.year,month_date.month)[1]).strftime("%Y/%m/%d")
imports are
from datetime import datetime, timedelta
from calendar import monthrange
you can add one condition for january so it will take december. If have any problem with that just add comment I will add that too.
How can I get the first date of the next month in Python? For example, if it's now 2019-12-31, the first day of the next month is 2020-01-01. If it's now 2019-08-01, the first day of the next month is 2019-09-01.
I came up with this:
import datetime
def first_day_of_next_month(dt):
'''Get the first day of the next month. Preserves the timezone.
Args:
dt (datetime.datetime): The current datetime
Returns:
datetime.datetime: The first day of the next month at 00:00:00.
'''
if dt.month == 12:
return datetime.datetime(year=dt.year+1,
month=1,
day=1,
tzinfo=dt.tzinfo)
else:
return datetime.datetime(year=dt.year,
month=dt.month+1,
day=1,
tzinfo=dt.tzinfo)
# Example usage (assuming that today is 2021-01-28):
first_day_of_next_month(datetime.datetime.now())
# Returns: datetime.datetime(2021, 2, 1, 0, 0)
Is it correct? Is there a better way?
Here is a 1-line solution using nothing more than the standard datetime library:
(dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)
Examples:
>>> dt = datetime.datetime(2016, 2, 29)
>>> print((dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1))
2016-03-01 00:00:00
>>> dt = datetime.datetime(2019, 12, 31)
>>> print((dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1))
2020-01-01 00:00:00
>>> dt = datetime.datetime(2019, 12, 1)
>>> print((dt.replace(day=1) + datetime.timedelta(days=32)).replace(day=1))
2020-01-01 00:00:00
Using dateutil you can do it the most literally possible:
import datetime
from dateutil import relativedelta
today = datetime.date.today()
next_month = today + relativedelta.relativedelta(months=1, day=1)
In English: add 1 month(s) to the today's date and set the day (of the month) to 1. Note the usage of singular and plural forms of day(s) and month(s). Singular sets the attribute to a value, plural adds the number of periods.
You can store this relativedelta.relativedelta object to a variable and the pass it around. Other answers involve more programming logic.
EDIT You can do it with the standard datetime library as well, but it's not so beautiful:
next_month = (today.replace(day=1) + datetime.timedelta(days=32)).replace(day=1)
sets the date to the 1st of the current month, adds 32 days (or any number between 31 and 59 which guarantees to jump into the next month) and then sets the date to the 1st of that month.
you can use calendar to get the number of days in a given month, then add timedelta(days=...), like this:
from datetime import date, timedelta
from calendar import monthrange
days_in_month = lambda dt: monthrange(dt.year, dt.month)[1]
today = date.today()
first_day = today.replace(day=1) + timedelta(days_in_month(today))
print(first_day)
if you're fine with external deps, you can use dateutil (which I love...)
from datetime import date
from dateutil.relativedelta import relativedelta
today = date.today()
first_day = today.replace(day=1) + relativedelta(months=1)
print(first_day)
Extract the year and month, add 1 and form a new date using the year, month and day=1:
from datetime import date
now = date(2020,12,18)
y,m = divmod(now.year*12+now.month,12)
nextMonth = date(y,m+1,1)
print(now,nextMonth)
# 2020-12-18 2021-01-01
Your way looks good yet I would have done it this way:
import datetime
from dateutil import relativedelta
dt = datetime.datetime(year=1998,
month=12,
day=12)
nextmonth = dt + relativedelta.relativedelta(months=1)
nextmonth.replace(day=1)
print(nextmonth)
Using only python standard libraries:
import datetime
today = datetime.date.today()
first_of_next_month = return date.replace(
day=1,
month=date.month % 12 + 1,
year=date.year + (date.month // 12)
)
could be generalized to...
def get_first_of_month(date, month_offset=0):
# zero based indexing of month to make math work
month_count = date.month - 1 + month_offset
return date.replace(
day=1, month=month_count % 12 + 1, year=date.year + (month_count // 12)
)
first_of_next_month = get_first_of_month(today, 1)
Other solutions that don't require 3rd party libraries include:
Toby Petty's answer is another good option.
If the exact timedelta is helpful to you,
a slight modification on Adam.Er8's answer might be convenient:
import calendar, datetime
today = datetime.date.today()
time_until_next_month = datetime.timedelta(
calendar.monthrange(today.year, today.month)[1] - today.day + 1
)
first_of_next_month = today + time_until_next_month
With Zope's DateTime library a very simple solution is possible
from DateTime.DateTime import DateTime
date = DateTime() # today
while date.day() != 1:
date += 1
print(date)
I see so many wonderful solutions to this problem I personally was looking for a solution for getting the first and last day of the previous month when I stmbled on this question.
But here is a solution I like to think is quite simple and elegant:
date = datetime.datetime.now().date()
same_time_next_month = date + datetime.timedelta(days = date.day)
first_day_of_next_month_from_date = same_time_next_month - datetime.timedelta(days = same_time_next_month.day - 1)
Here we simply add the day of the target date to the date to get the same time of the next month, and then remove the number of days elapsed from the new date gotten.
Try this, for starting day of each month, change MonthEnd(1) to MonthBegin(1):
import pandas as pd
from pandas.tseries.offsets import MonthBegin, MonthEnd
date_list = (pd.date_range('2021-01-01', '2022-01-31',
freq='MS') + MonthEnd(1)).strftime('%Y-%m-%d').tolist()
date_list
Out:
['2021-01-31',
'2021-02-28',
'2021-03-31',
'2021-04-30',
'2021-05-31',
'2021-06-30',
'2021-07-31',
'2021-08-31',
'2021-09-30',
'2021-10-31',
'2021-11-30',
'2021-12-31',
'2022-01-31']
With python-dateutil:
from datetime import date
from dateutil.relativedelta import relativedelta
last day of current month:
date.today() + relativedelta(day=31)
first day of next month:
date.today() + relativedelta(day=31) + relativedelta(days=1)
I want to get the 20th of previous month, given the current_date()
I am trying to use time.strftime but not able to subtract the value from it.
timestr = time.strftime("%Y-(%m-1)%d")
This is giving me error. The expected output is 2019-03-20 if my current_date is in April. Not sure how to go about it.
I read the posts from SO and most of them address getting the first day / last day of the month. Any help would be appreciated.
from datetime import date, timedelta
today = date.today()
last_day_prev_month = today - timedelta(days=today.day)
twenty_prev_month = last_day_prev_month.replace(day=20)
print(twenty_prev_month) # 2019-03-20
Use datetime.replace
import datetime
current_date = datetime.date.today()
new_date = current_date.replace(
month = current_date.month - 1,
day = 20
)
print(new_date)
#2019-03-20
Edit
That won't work for Jan so this is a workaround:
import datetime
current_date = datetime.date(2019, 2, 17)
month = current_date.month - 1
year = current_date.year
if not month:
month, year = 12, year - 1
new_date = datetime.date(year=year, month=month, day=20)
I imagine it is the way dates are parsed. It is my understanding that with your code it is looking for
2019-(03-1)20 or 2019-(12-1)15, etc..
Because the %y is not a variable, but a message about how the date is to be expected within a string of text, and other characters are what should be expected, but not processed (like "-")
This seems entirely not what you are going for. I would just parse the date like normal and then reformat it to be a month earlier:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
print("{}-{}-{}".format(year, int(month)-1, day))
This would be easier with timedelta objects, but sadly there isn't one for months, because they are of various lengths.
To be more robust if a new year is involved:
import datetime
time = datetime.datetime.today()
print(time)
timestr = time.strftime("%Y-%m-%d")
year, month, day = timestr.split("-")
if month in [1, "01", "1"]: # I don't remember how January is represented
print("{}-{}-{}".format(int(year) - 1, 12, day)) # use December of last year
else:
print("{}-{}-{}".format(year, int(month)-1, day))
This will help:
from datetime import date, timedelta
dt = date.today() - timedelta(30)// timedelta(days No.)
print('Current Date :',date.today())
print(dt)
It is not possible to do math inside a string passed to time.strftime, but you can do something similar to what you're asking very easily using the time module
in Python 3
# Last month
t = time.gmtime()
print(f"{t.tm_year}-{t.tm_mon-1}-20")
or in Python 2
print("{0}-{1}-{2}".format(t.tm_year, t.tm_mon -1, 20))
If you have fewer constraints, you can just use the datetime module instead.
You could use datetime, dateutil or arrow to find the 20th day of the previous month. See examples below.
Using datetime:
from datetime import date
d = date.today()
month, year = (d.month-1, d.year) if d.month != 1 else (12, d.year-1)
last_month = d.replace(day=20, month=month, year=year)
print(last_month)
Using datetime and timedelta:
from datetime import date
from datetime import timedelta
d = date.today()
last_month = (d - timedelta(days=d.day)).replace(day=20)
print(last_month)
Using datetime and dateutil:
from datetime import date
from dateutil.relativedelta import relativedelta # pip install python-dateutil
d = date.today()
last_month = d.replace(day=20) - relativedelta(months=1)
print(last_month)
Using arrow:
import arrow # pip install arrow
d = arrow.now()
last_month = d.shift(months=-1).replace(day=20).datetime.date()
print(last_month)
In Python can you select a random date from a year. e.g. if the year was 2010 a date returned could be 15/06/2010
It's much simpler to use ordinal dates (according to which today's date is 734158):
from datetime import date
import random
start_date = date.today().replace(day=1, month=1).toordinal()
end_date = date.today().toordinal()
random_day = date.fromordinal(random.randint(start_date, end_date))
This will fail for dates before 1AD.
Not directly, but you could add a random number of days to January 1st. I guess the following should work for the Gregorian calendar:
from datetime import date, timedelta
import random
import calendar
# Assuming you want a random day of the current year
firstJan = date.today().replace(day=1, month=1)
randomDay = firstJan + timedelta(days = random.randint(0, 365 if calendar.isleap(firstJan.year) else 364))
import datetime, time
import random
def year_start(year):
return time.mktime(datetime.date(year, 1, 1).timetuple())
def rand_day(year):
stamp = random.randrange(year_start(year), year_start(year + 1))
return datetime.date.fromtimestamp(stamp)
Edit: Ordinal dates as used in Michael Dunns answer are way better to use then timestamps! One might want to combine the use of ordinals with this though.
import calendar
import datetime
import random
def generate_random_date(future=True, years=1):
today = datetime.date.today()
#Set the default dates
day = today.day
year = today.year
month = today.month
if future:
year = random.randint(year, year + years)
month = random.randint(month, 12)
date_range = calendar.monthrange(year, month)[1] #dates possible this month
day = random.randint(day + 1, date_range) #1 day in the future
else:
year = random.randint(year, year - years)
month = random.randint(1, month)
day = random.randint(1, day - 1)
return datetime.date(year, month, day)
This is an old question, but, you can use my new library ^_^ chancepy here
from chancepy import Chance
randomDate = Chance.date(year=2020)
To get a random date you can use faker
pip install faker
from faker import Faker
fake = Faker()
fake.date_between(start_date='today', end_date='+1y')
if you want from the beginning of the year then:
start_date = datetime.date(year=2023, month=1, day=1)
fake.date_between(start_date, end_date='+1y')