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

Question:

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.

Asked By: planetp

||

Answers:

I get an OSError: [Errno 22] Invalid argument using Python 3.6. This is what the documentation says:

Note

There is no method to obtain the POSIX timestamp directly from a naive datetime instance representing UTC time. If your application uses this convention and your system timezone is not set to UTC, you can obtain the POSIX timestamp by supplying tzinfo=timezone.utc:

timestamp = dt.replace(tzinfo=timezone.utc).timestamp()

or by calculating the timestamp directly:

timestamp = (dt - datetime(1970, 1, 1)) / timedelta(seconds=1)

So when I tried:

>>> import datetime
>>> datetime.datetime.max.replace(tzinfo=datetime.timezone.utc).timestamp()
253402300800.0
Answered By: Ronald

your syntax is incorrect ..
datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
The year, month and day arguments are required. tzinfo may be None, or an instance of a tzinfo subclass. The remaining arguments must be integers in the following ranges:

MINYEAR <= year <= MAXYEAR,

1 <= month <= 12,

1 <= day <= number of days in the given month and year,

0 <= hour < 24,

0 <= minute < 60,

0 <= second < 60,

0 <= microsecond < 1000000,

fold in [0, 1].

Answered By: user13531614

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.

Answered By: Vinay Gupta

The actual reason is datetime.timestamp() returns POSIX timestamp that overflows in 2038, and datetime.max is in year 9999.

Search online for "Year 2038 problem" for more information.

Answered By: Sergey M