Skip to content

Commit

Permalink
Merge pull request #16 from brian7704/main
Browse files Browse the repository at this point in the history
Fix datetime parsing for newer TAK clients that don't include microseconds in the timestamp
  • Loading branch information
ampledata authored Jun 22, 2024
2 parents 682dc64 + 65125bd commit 24bf0fa
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 2 deletions.
2 changes: 1 addition & 1 deletion takproto/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@
DEFAULT_MESH_HEADER = bytearray(b"\xbf\x01\xbf")

W3C_XML_DATETIME: str = "%Y-%m-%dT%H:%M:%S.%fZ"
ISO_8601_UTC = W3C_XML_DATETIME # Issue 7: Not technically correct.
ISO_8601_UTC: str = "%Y-%m-%dT%H:%M:%SZ"


class TAKProtoVer(Enum):
Expand Down
6 changes: 5 additions & 1 deletion takproto/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@

from takproto.constants import (
ISO_8601_UTC,
W3C_XML_DATETIME,
DEFAULT_MESH_HEADER,
DEFAULT_PROTO_HEADER,
TAKProtoVer,
Expand Down Expand Up @@ -70,7 +71,10 @@ def parse_stream(msg):

def format_time(time: str) -> int:
"""Format timestamp as microseconds."""
s_time = datetime.strptime(time + "+0000", ISO_8601_UTC + "%z")
try:
s_time = datetime.strptime(time, ISO_8601_UTC)
except ValueError:
s_time = datetime.strptime(time, W3C_XML_DATETIME)
return int(s_time.timestamp() * 1000)


Expand Down
13 changes: 13 additions & 0 deletions tests/test_functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,19 @@ def test_format_timestamp(self):
)
self.assertEqual(time2, t_time)

def test_format_timestamp_without_subseconds(self):
"""Test formatting timestamp to and from Protobuf format."""
t_time = "2020-02-08T18:10:44Z"
t_ts = 1581185444000
ts = takproto.format_time(t_time)
self.assertEqual(ts, t_ts)

t_ts2 = t_ts / 1000
time2 = datetime.fromtimestamp(t_ts2, timezone.utc).strftime(
"%Y-%m-%dT%H:%M:%SZ"
)
self.assertEqual(time2, t_time)

def test_xml2proto_default(self):
"""Test encoding XML string as Protobuf bytearray."""
t_xml = """<?xml version='1.0' encoding='UTF-8' standalone='yes'?>
Expand Down

0 comments on commit 24bf0fa

Please sign in to comment.