Search code examples
pythonpython-datetimepython-3.8

Why do I get a ValueError when using datetime.max?


Why do I get a ValueError in this example?

>>> import datetime
>>> datetime.datetime.max.timestamp()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: year 10000 is out of range

I'm using Python 3.8.3.


Solution

  • timestamp() method actually converts your datetime in local timezone. If your timezone is UTC+x (not UTC-x); i.e. your timezone is ahead of UTC time; Then it will add more time in your datetime object (datetime.datetime.max) which will cross the time beyond the year 9999. That is why your code gives that error.

    Below is an example to validate it:

    val1 = datetime.datetime.now()  # datetime.datetime(2020, 6, 15, 15, 54, 15, 214349)
    

    val1 is the exact time in my timezone, but there is no timezone associated with it (so it will take local timezone as datetime.datetime.max would take). You can check the timezone in datetime object using val1.tzinfo. If it returns blank, that means code assumes the time is in local timezone.

    I have created one more object with same time but in UTC timezone:

    val2 = datetime.datetime.fromisoformat("2020-06-15T15:54:15.214349+00:00")
    

    I print the values:

    print(val1.timestamp()) # 1592216655.214349
    print(val2.timestamp()) # 1592236455.214349
    

    If you calculate the difference between the two values, it will give 19,800 seconds (which is 5.5 hours), which is exactly my timezone (IST or you can say UTC+5:30) difference from UTC.