Skip to content

Commit

Permalink
Update datetime parser to support negative timestamps (#1605)
Browse files Browse the repository at this point in the history
- Negative timestamps corresponds to dates before 1970/1/1
  • Loading branch information
mlbiche committed Jun 27, 2020
1 parent 7bd635c commit 113921c
Show file tree
Hide file tree
Showing 4 changed files with 4 additions and 2 deletions.
1 change: 1 addition & 0 deletions changes/1600-mlbiche.md
@@ -0,0 +1 @@
Update datetime parser to support negative timestamps
2 changes: 1 addition & 1 deletion docs/usage/types.md
Expand Up @@ -248,7 +248,7 @@ types:
* `datetime` fields can be:

* `datetime`, existing `datetime` object
* `int` or `float`, assumed as Unix time, i.e. seconds (if <= `2e10`) or milliseconds (if > `2e10`) since 1 January 1970
* `int` or `float`, assumed as Unix time, i.e. seconds (if >= `-2e10` or <= `2e10`) or milliseconds (if < `-2e10`or > `2e10`) since 1 January 1970
* `str`, following formats work:

* `YYYY-MM-DD[T]HH:MM[:SS[.ffffff]][Z[±]HH[:]MM]]]`
Expand Down
2 changes: 1 addition & 1 deletion pydantic/datetime_parse.py
Expand Up @@ -75,7 +75,7 @@ def get_numeric(value: StrBytesIntFloat, native_expected_type: str) -> Union[Non


def from_unix_seconds(seconds: Union[int, float]) -> datetime:
while seconds > MS_WATERSHED:
while abs(seconds) > MS_WATERSHED:
seconds /= 1000
dt = EPOCH + timedelta(seconds=seconds)
return dt.replace(tzinfo=timezone.utc)
Expand Down
1 change: 1 addition & 0 deletions tests/test_datetime_parse.py
Expand Up @@ -93,6 +93,7 @@ def test_time_parsing(value, result):
(1_494_012_444, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)),
# values in ms
('1494012444000.883309', datetime(2017, 5, 5, 19, 27, 24, 883, tzinfo=timezone.utc)),
('-1494012444000.883309', datetime(1922, 8, 29, 4, 32, 35, 999117, tzinfo=timezone.utc)),
(1_494_012_444_000, datetime(2017, 5, 5, 19, 27, 24, tzinfo=timezone.utc)),
('2012-04-23T09:15:00', datetime(2012, 4, 23, 9, 15)),
('2012-4-9 4:8:16', datetime(2012, 4, 9, 4, 8, 16)),
Expand Down

0 comments on commit 113921c

Please sign in to comment.