Why can't python's datetime.max survive a round trip through timestamp / fromtimestamp?
<p>In most cases I can round-trip datetimes to and from a timestamp as follows:</p>

<pre><code>from datetime import datetime

dt = datetime(2016, 1, 1, 12, 34, 56, 789)
print(dt)
print(datetime.fromtimestamp(dt.timestamp()))
</code></pre>

<blockquote>
  <p>2016-01-01 12:34:56.000789</p>
  
  <p>2016-01-01 12:34:56.000789</p>
</blockquote>

<p>But this doesn't work for datetime.max. Why is that?</p>

<pre><code>dt = datetime.max
print(dt)
print(datetime.fromtimestamp(dt.timestamp()))
</code></pre>

<blockquote>
  <p>9999-12-31 23:59:59.999999</p>
  
  <p>Traceback (most recent call last):   File
  "python", line 9, in  ValueError: year is out of range</p>
</blockquote>

<p>More precisely, why hasn't the datetime library taken this case into account?</p>

<p>Simply because the maximum of a datetime object is not the same as the maximum of a valid timestamp.</p>

<p>There's also a good reason to limit the range of timestamps: they are but a simple python <code>float</code>, which, on "normal" machines are double precision floating points. But: you lose more than a couple of seconds in precision:</p>

<pre><code>print(datetime.max.timestamp())
253402297200.0
print(datetime.max.second)
59
print(datetime.max.microsecond)
999999
</code></pre>

<p><strong>spot the error.</strong></p>

<p>Timestamps based on floating point numbers are, <em>by definition</em> less accurate the more they are in the future. So not being able to represent arbitrary valid <code>datetimes</code> in a timestamp is perfectly reasonable, just as restricting one a couple thousand years in the future.</p>

<p>so:</p>

<blockquote>
  <p>More precisely, why hasn't the datetime library taken this case into account?</p>
</blockquote>

<p>Because timestamps so far in the future are unreliably and very likely do not represent the time you've meant, so rejecting them is a wise thing.</p>

<p>Takeaway: a floating point number like <code>timestamp()</code> produces is not an appropriate way of transporting times with fixed precision. If you at all can, avoid it.</p>

python python-3.x datetime