0

I need to calculate the number of days between two dates. One will be today and the other one is -2580,01,01.

I have tried with the datetime library but I can't because the datetime library don't accept negative years (MIN=1, MAX=9999).

I have tried with dateutil.relativedelta:

from datetime import *
from dateutil.relativedelta import *
import calendar

RightNOW = datetime.now() # with full time
JustTODAY = date.today() # only days

PastTime = JustTODAY+relativedelta(years=-4600)

print(PastTime)
Traceback (most recent call last):
  File "GoblinTest.py", line 11, in <module>
    PastTime = JustTODAY+relativedelta(years=-4600)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 405, in __radd__
    return self.__add__(other)
  File "/usr/lib/python3.8/site-packages/dateutil/relativedelta.py", line 387, in __add__
    ret = (other.replace(**repl)
ValueError: year -2580 is out of range
martineau
  • 119,623
  • 25
  • 170
  • 301
  • One of the main issues is that exact dates become quite hazy that far in the past… what kind of calculation are you trying to do here and what sort of accuracy do you expect for your results? – deceze Feb 16 '20 at 09:09
  • If you are only interessted in relative numbers (and do not care if you are off by a day or two) you could simply shift the time scale and calculate the days between today and today + offset (4600) – 465b Feb 16 '20 at 09:15
  • 1
    You may be able to use a third-party module like [jdcal](https://pypi.org/project/jdcal/) because: '[all the] functions are "proleptic”. This means that they work for dates on which the concerned calendar is not valid.' – martineau Feb 16 '20 at 10:18

2 Answers2

0

The issue is that datetime only supports years > 0 for datetime.

>>> datetime.datetime(2,1,1) - relativedelta(years=1)
datetime.datetime(1, 1, 1, 0, 0)
>>> datetime.datetime(2,1,1) - relativedelta(years=2)
ValueError: year 0 is out of range

As stated in the docs:

The datetime module exports the following constants: datetime.MINYEAR The smallest year number allowed in a date or datetime object. MINYEAR is 1.

abc
  • 11,579
  • 2
  • 26
  • 51
0

Do a work around by accepting the limitations of the dateutil module and the datetime module.

Use years=1, and manually add in the previous days: 2581 * 365 = 942065.

This gives you limited accuracy; and you'd need to state, and account for, those assumptions in your application.

David Collins
  • 848
  • 3
  • 10
  • 28