I am using the datetime Python module. I am looking to calculate the date 3 months from the input date. Can you help me to get out of this issue.Thanks in advance
import datetime
today = "2022-02-24"
three = today + datetime.timedelta(30*3)
print (three)
Also I tried using "relativedelta"
You can't add a timedelta to a string, you need to add it to a datetime instance
Note that 90 days, isn't really 3 months
from datetime import datetime, timedelta
today = "2022-02-24"
three = datetime.strptime(today, "%Y-%m-%d") + timedelta(30 * 3)
print(three) # 2022-05-25 00:00:00
three = datetime.today() + timedelta(30 * 3)
print(three) # 2022-05-24 21:32:35.048700
With relativedelta of dateutil package, you can use:
from dateutil.relativedelta import relativedelta
from datetime import date
three = date.today() + relativedelta(months=3)
Output:
>>> three
datetime.date(2022, 5, 23)
I need to subtract 1 day from the current date and time? How would i do that?
Here is my code:
from datetime import datetime
now = datetime.now()
date = (now.strftime("%Y-%m-%d %H:%M:%S"))
print(date)
Say the date is (2021-10-3) i need the time variable to be set to something like (2021-10-2) Changing the day by -1 day!
Use timedelta.
from datetime import datetime, timedelta
now = datetime.now()
yesterday = now - timedelta(days=1)
date = (yesterday.strftime("%Y-%m-%d %H:%M:%S"))
print(date)
Find more about timedelta here
I am trying to print only the month and date in python as following :
09-December
08-October
How could I do that?
Try this
import datetime
now = datetime.datetime.now()
print now.strftime("%d-%B")
For more information on this : strftime
from datetime import datetime
dt = datetime.strptime("09/12/16", "%d/%m/%y")
dt.strftime("%d-%B")
from datetime import date
d = date(2016, 12, 9)
d.strftime("%d - %A")
# 9 - Friday
# month day year
#d.strftime("%A %d %B %Y")
Very new to python, please excuse the noob question:
I have a number that represents a date like :
date = 20121228
( representing December 28th, 2012)
How can I increment that date by 5 days in python so I end up with a new (correct) number representing the date like
date = 20130102
I don't want:
date = 20121233
Update: When I try and use datetime.strptime I get this error:
Traceback (most recent call last):
File "<stdin>", line 1, in ?
AttributeError: type object 'datetime.datetime' has no attribute 'strptime'
Try this:
date = 20121228
from datetime import datetime, timedelta
dt = datetime.strptime(str(date), "%Y%m%d").date() + timedelta(days=5)
print datetime.strftime(dt, "%Y%m%d")
Parse it to a datetime.date() object, add 5 days, then reformat back to your number:
from datetime import datetime, timedelta
dt = datetime.strptime(str(date), '%Y%m%d').date()
dt += timedelta(days=5)
date = int(dt.strftime('%Y%m%d'))
Demonstration:
>>> from datetime import datetime, timedelta
>>> date = 20121228
>>> dt = datetime.strptime(str(date), '%Y%m%d').date()
>>> dt += timedelta(days=5)
>>> int(dt.strftime('%Y%m%d'))
20130102
For Python versions before Python 2.5, you'll need to use the time.strptime() version:
import time
from datetime import datetime, timedelta
dt = datetime(*(time.strptime(str(date), '%Y%m%d')[:6]))
dt += timedelta(days=5)
date = int(dt.strftime('%Y%m%d'))
You'll need to convert your date into a string first. Then use a timedelta object to add the days to the datetime object.
from datetime import datetime, timedelta
d = datetime.strptime(str(20121228), "%Y%m%d")
print (d + timedelta(days=5)).strftime("%Y%m%d")
i know using datetime.timedelta i can get the date of some days away form given date
daysafter = datetime.date.today() + datetime.timedelta(days=5)
but seems no datetime.timedelta(month=1)
Use dateutil module. It has relative time deltas:
import datetime
from dateutil import relativedelta
nextmonth = datetime.date.today() + relativedelta.relativedelta(months=1)
Beautiful.
Of course there isn't -- if today's January 31, what would be "the same day of the next month"?! Obviously there is no right solution, since February 31 does not exist, and the datetime module does not play at "guess what the user posing this impossible problem without a right solution thinks (wrongly) is the obvious solution";-).
I suggest:
try:
nextmonthdate = x.replace(month=x.month+1)
except ValueError:
if x.month == 12:
nextmonthdate = x.replace(year=x.year+1, month=1)
else:
# next month is too short to have "same date"
# pick your own heuristic, or re-raise the exception:
raise
You can use calendar.nextmonth (from Python 3.7).
>>> import calendar
>>> calendar.nextmonth(year=2019, month=6)
(2019, 7)
>>> calendar.nextmonth(year=2019, month=12)
(2020, 1)
But be aware that this function isn't meant to be public API, it's used internally in calendar.Calendar.itermonthdays3() method. That's why it doesn't check the given month value:
>>> calendar.nextmonth(year=2019, month=60)
(2019, 61)
In Python 3.8 is already implemented as internal function.
from calendar import mdays
from datetime import datetime, timedelta
today = datetime.now()
next_month_of_today = today + timedelta(mdays[today.month])
I don't want to import dateutil. Have a try this. Good luck.
import calendar, datetime
def next_month ( date ):
"""return a date one month in advance of 'date'.
If the next month has fewer days then the current date's month, this will return an
early date in the following month."""
return date + datetime.timedelta(days=calendar.monthrange(date.year,date.month)[1])
This work for me
import datetime
import calendar
def next_month_date(d):
_year = d.year+(d.month//12)
_month = 1 if (d.month//12) else d.month + 1
next_month_len = calendar.monthrange(_year,_month)[1]
next_month = d
if d.day > next_month_len:
next_month = next_month.replace(day=next_month_len)
next_month = next_month.replace(year=_year, month=_month)
return next_month
usage:
d = datetime.datetime.today()
print next_month_date(d)
This is how I solved it.
from datetime import datetime, timedelta
from calendar import monthrange
today_date = datetime.now().date() # 2021-10-29
year = today_date.year
month = today_date.month
days_in_month = monthrange(year, month)[1]
next_month = today_date + timedelta(days=days_in_month)
print(next_month) # 2021-11-29
Solution on Python3 without additional modules nor internal functions.
from datetime import date
today = date.today()
nextMonth = date(today.year+((today.month+1)//12) , ((today.month+1)%12), today.day)
Hurray for integer algebra!
from datetime import timedelta
try:
next_month = (x.replace(day=28) + timedelta(days=7)).replace(day=x.day)
except ValueError: # assuming January 31 should return last day of February.
next_month = (x + timedelta(days=31)).replace(day=1) - timedelta(days=1)
from dateutil.relativedelta import relativedelta
from dateutil import parser
d2 = "1/4/2022 8:39:23 AM"
NextMonth = parser.parse(d2) + relativedelta(months=+1) + relativedelta(days=-1)
print(NextMonth)
This is how I solved it.
from datetime import date
try:
(year, month) = divmod(date.today().month, 12)
next_month = date.today().replace(year=date.today().year+year, month=month+1)
except ValueError:
# This day does not exist in next month
You can skip the try/catch if you only want the first day in next month by setting replace(year=date.today().year+year, month=month, day=1). This will always be a valid date since we have caught the month overflow using divmod.
I often need to need to keep the date as last in month when adding months. I try to add the amount of months to the day after and then remove one day again. If that fails I add one more day until success.
from datetime import timedelta
DAY = timedelta(1)
def add_months(d, months):
"Add months to date and retain last day in month."
d += DAY
# calculate year diff and zero based month
y, m = divmod(d.month + months - 1, 12)
try:
return d.replace(d.year + y, m + 1) - DAY
except ValueError:
# on fail return last day in month
# can't fail on december so just adding one more month
return d.replace(d.year + y, m + 2, 1) - DAY
This Code Works for me:
NextMonth = self.CurruntMonth.replace(day=15) + datetime.timedelta(days=30)