Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Support timestamps without microseconds #19

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions takproto/constants.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@
DEFAULT_PROTO_HEADER = bytearray(b"\xbf")
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.
W3C_XML_DATETIME: str = "%Y-%m-%dT%H:%M:%SZ"
ISO_8601_UTC: str = "%Y-%m-%dT%H:%M:%S.%fZ"


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 + "+0000", W3C_XML_DATETIME + "%z")
except ValueError:
s_time = datetime.strptime(time + "+0000", ISO_8601_UTC + "%z")
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
Loading