mirror of
https://github.com/ihabunek/toot.git
synced 2025-05-18 00:58:30 -04:00
Use dateutil to parse datetimes
This solves the problem of various servers returning differently formatted datetimes. issue #523
This commit is contained in:
parent
baf591cfe7
commit
4d72b1b6c8
@ -1,8 +1,10 @@
|
||||
from datetime import datetime
|
||||
import click
|
||||
import pytest
|
||||
import sys
|
||||
|
||||
from toot.cli.validators import validate_duration
|
||||
from toot.utils.datetime import parse_datetime
|
||||
from toot.wcstring import wc_wrap, trunc, pad, fit_text
|
||||
from toot.tui.utils import LRUCache
|
||||
from PIL import Image
|
||||
@ -331,3 +333,37 @@ def test_batched():
|
||||
|
||||
with pytest.raises(ValueError):
|
||||
list(batched("foo", 0))
|
||||
|
||||
|
||||
def test_parse_datetime():
|
||||
# mastodon uses this format
|
||||
dt = parse_datetime("2023-07-21T13:27:45.996+00:00")
|
||||
assert dt_tuple(dt) == (2023, 7, 21, 13, 27, 45, 0)
|
||||
|
||||
dt = parse_datetime("2023-07-21T13:27:45.996+01:00")
|
||||
assert dt_tuple(dt) == (2023, 7, 21, 12, 27, 45, 0)
|
||||
|
||||
dt = parse_datetime("2023-07-21T13:27:45.996-06:00")
|
||||
assert dt_tuple(dt) == (2023, 7, 21, 19, 27, 45, 0)
|
||||
|
||||
# snac2 uses this format
|
||||
dt = parse_datetime("2023-12-29T09:22:15Z")
|
||||
assert dt_tuple(dt) == (2023, 12, 29, 9, 22, 15, 0)
|
||||
|
||||
|
||||
def dt_tuple(dt: datetime):
|
||||
assert isinstance(dt, datetime)
|
||||
|
||||
# Parsing should create an aware datetime object
|
||||
offset = dt.utcoffset()
|
||||
assert offset is not None
|
||||
|
||||
return (
|
||||
dt.year,
|
||||
dt.month,
|
||||
dt.day,
|
||||
dt.hour,
|
||||
dt.minute,
|
||||
dt.second,
|
||||
offset.total_seconds()
|
||||
)
|
||||
|
@ -2,11 +2,12 @@ import math
|
||||
import os
|
||||
|
||||
from datetime import datetime, timezone
|
||||
from dateutil.parser import parse
|
||||
|
||||
|
||||
def parse_datetime(value: str) -> datetime:
|
||||
"""Returns an aware datetime in local timezone"""
|
||||
dttm = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%f%z")
|
||||
dttm = parse(value)
|
||||
|
||||
# When running tests return datetime in UTC so that tests don't depend on
|
||||
# the local timezone
|
||||
|
Loading…
x
Reference in New Issue
Block a user