Python Forum

Full Version: How to add date and years(integer) to get a date
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
I am trying to add years in integer form in date to get final output as date. Could anyone help with syntax.
show us what have you tried, sample input and expected output

probably https://docs.python.org/3/library/dateti...te.replace or https://docs.python.org/3/library/dateti...me.replace
What have you tried? Show us your code and where you are stuck. Have you tried timedelta(days=years*365) but got stuck on leap years?
(Sep-02-2020, 07:22 PM)NG0824 Wrote: [ -> ]I am trying to add years in integer form in date to get final output as date. Could anyone help with syntax.

In [1]: import datetime

In [2]: now = datetime.datetime.now()

In [3]: print(now)
2020-09-03 10:01:22.062401

In [4]: # set a year
   ...: past = now.replace(year=1900)

In [5]: print(past)
1900-09-03 10:01:22.062401

In [6]: # adding years to current year
   ...: future = now.replace(now.year + 10) # 10 years in future

In [7]: leap_year = datetime.datetime(2020, 2, 29) # impossible date for non-leap years

In [8]: print(leap_year)
2020-02-29 00:00:00

In [9]: leap_year.replace(year=2019)  # booom
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-9-164fec2883be> in <module>
----> 1 leap_year.replace(year=2019)  # booom

ValueError: day is out of range for month
If you wonder, this comes from IPython. A better REPL for Python.
Working with dates is not always straightforward. Sometimes it ends into impossible dates.

To catch this leap_error:

import datetime

one_day = datetime.timedelta(days=1)
leap_year = datetime.datetime(2020, 2, 29)
new_year = 2019

try:
    new_dt = leap_year.replace(year=new_year)
except ValueError:
    new_dt = (leap_year + one_day).replace(year=new_year)
Important stuff to read:
I hope this pushes you in the right direction.
Just keep in mind, that the replace method does not change the object itself, it returns a new modified datetime object.
Thanks everyone, I was able to solve this error by firt installing datedelta and then used datedelat.datedelta(years=fieldname())