(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 monthIf 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:
- https://docs.python.org/3/library/dateti...ta-objects
- Call signature of datetime: https://docs.python.org/3/library/dateti...me-objects
- Replace return a new date: https://docs.python.org/3/library/dateti...me.replace
- To check if a year is a leap year: https://docs.python.org/3/library/calend...dar.isleap
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.
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
All humans together. We don't need politicians!