Commit 659ee98
authored
Fix Timestamp.from_datetime() precision for far-future datetimes (#710)
`Timestamp.from_datetime()` computes the whole-second part from the
float `datetime.timestamp()`. A float64 cannot hold microsecond
precision for datetimes far from the epoch, so `timestamp()` rounds the
seconds up while the exact `microsecond` is still used for the
nanoseconds. The result is a `Timestamp` one second in the future, and
near `datetime.max` it raises `OverflowError`:
```python
>>> import datetime as dt
>>> from msgpack.ext import Timestamp
>>> d = dt.datetime(3000, 1, 1, 0, 0, 0, 999999, tzinfo=dt.timezone.utc)
>>> Timestamp.from_datetime(d).to_datetime()
datetime.datetime(3000, 1, 1, 0, 0, 1, 999999, tzinfo=datetime.timezone.utc) # +1 second
>>> Timestamp.from_datetime(dt.datetime(9999, 12, 31, 23, 59, 59, 999999, tzinfo=dt.timezone.utc))
OverflowError: date value out of range
```
The Cython packer already uses integer `timedelta` arithmetic and is
correct. This makes the pure-Python `from_datetime()` do the same, so
the two paths agree and the round-trip invariant
`from_datetime(d).to_datetime() == d` holds for far-future datetimes.
Naive datetimes keep their existing local-time interpretation (matching
`datetime.timestamp()`).
Follow-up to #662, which fixed the pre-epoch rounding direction in the
same method.
Existing tests are unchanged; I added a regression test covering the
far-future round-trip, the exact seconds/nanoseconds, agreement with
packing the datetime directly, and the former `OverflowError` case. Full
suite is green on both the C-extension and pure-Python paths.1 parent d5e380f commit 659ee98
2 files changed
Lines changed: 51 additions & 3 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
2 | 2 | | |
3 | 3 | | |
4 | 4 | | |
| 5 | + | |
| 6 | + | |
5 | 7 | | |
6 | 8 | | |
7 | 9 | | |
| |||
156 | 158 | | |
157 | 159 | | |
158 | 160 | | |
159 | | - | |
160 | | - | |
| 161 | + | |
161 | 162 | | |
162 | 163 | | |
163 | 164 | | |
| |||
167 | 168 | | |
168 | 169 | | |
169 | 170 | | |
170 | | - | |
| 171 | + | |
| 172 | + | |
| 173 | + | |
| 174 | + | |
| 175 | + | |
| 176 | + | |
| 177 | + | |
| 178 | + | |
| 179 | + | |
| 180 | + | |
| 181 | + | |
| 182 | + | |
| 183 | + | |
| 184 | + | |
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
111 | 111 | | |
112 | 112 | | |
113 | 113 | | |
| 114 | + | |
| 115 | + | |
| 116 | + | |
| 117 | + | |
| 118 | + | |
| 119 | + | |
| 120 | + | |
| 121 | + | |
| 122 | + | |
| 123 | + | |
| 124 | + | |
| 125 | + | |
| 126 | + | |
| 127 | + | |
| 128 | + | |
| 129 | + | |
| 130 | + | |
| 131 | + | |
| 132 | + | |
| 133 | + | |
| 134 | + | |
| 135 | + | |
| 136 | + | |
| 137 | + | |
| 138 | + | |
| 139 | + | |
| 140 | + | |
| 141 | + | |
| 142 | + | |
| 143 | + | |
| 144 | + | |
| 145 | + | |
| 146 | + | |
| 147 | + | |
114 | 148 | | |
115 | 149 | | |
116 | 150 | | |
| |||
0 commit comments