diff --git a/src/statd/python/yanger/common.py b/src/statd/python/yanger/common.py index 2697fced..be0c3ef9 100644 --- a/src/statd/python/yanger/common.py +++ b/src/statd/python/yanger/common.py @@ -1,5 +1,28 @@ +from datetime import timedelta + +from . import host + LOG = None +class YangDate: + def __init__(self, dt=None): + self.dt = dt if dt else host.HOST.now() + + def __str__(self): + datestr = self.dt.strftime("%Y-%m-%dT%H:%M:%S%z") + + # Translate strftime's timezone format (HHMM) to the one + # expected by YANG (HH:MM) + return datestr[:-2] + ':' + datestr[-2:] + + @classmethod + def from_delta(cls, delta): + return cls(host.HOST.now() - delta) + + @classmethod + def from_seconds(cls, seconds): + return cls.from_delta(timedelta(seconds=seconds)) + def insert(obj, *path_and_value): """"This function inserts a value into a nested json object""" diff --git a/src/statd/python/yanger/ietf_routing.py b/src/statd/python/yanger/ietf_routing.py index d9737d9c..4ac89009 100644 --- a/src/statd/python/yanger/ietf_routing.py +++ b/src/statd/python/yanger/ietf_routing.py @@ -1,10 +1,9 @@ from datetime import timedelta from re import match -from .common import insert +from .common import insert, YangDate from .host import HOST - def uptime2datetime(uptime): """ Convert uptime to YANG format (YYYY-MM-DDTHH:MM:SS+00:00) @@ -36,11 +35,7 @@ def uptime2datetime(uptime): h += days * 24 uptime_delta = timedelta(hours=h, minutes=m, seconds=s) - current_time = HOST.now() - last_updated = current_time - uptime_delta - date_timestd = last_updated.strftime('%Y-%m-%dT%H:%M:%S%z') - - return date_timestd[:-2] + ':' + date_timestd[-2:] + return str(YangDate.from_delta(uptime_delta)) def add_protocol(routes, proto):