Python Forum
How to add date and years(integer) to get a date - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: How to add date and years(integer) to get a date (/thread-29448.html)



How to add date and years(integer) to get a date - NG0824 - Sep-02-2020

I am trying to add years in integer form in date to get final output as date. Could anyone help with syntax.


RE: How to add date and years(integer) to get a date - buran - Sep-02-2020

show us what have you tried, sample input and expected output

probably https://docs.python.org/3/library/datetime.html#datetime.date.replace or https://docs.python.org/3/library/datetime.html#datetime.datetime.replace


RE: How to add date and years(integer) to get a date - jefsummers - Sep-02-2020

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?


RE: How to add date and years(integer) to get a date - DeaD_EyE - Sep-03-2020

(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.


RE: How to add date and years(integer) to get a date - NG0824 - Sep-03-2020

Thanks everyone, I was able to solve this error by firt installing datedelta and then used datedelat.datedelta(years=fieldname())