Time: Add some rudimentary time & time-formatting functions to CalvinLib
# limitations under the License.
from calvin.runtime.south.calvinlib import base_calvinlib_object
+from calvin.utilities.calvinlogger import get_logger
import time
import datetime
+_log = get_logger(__name__)
+
+
class Time(base_calvinlib_object.BaseCalvinlibObject):
"""
- Functions for handling time.
+ Functions for formatting and getting time
"""
init_schema = {
- "description": "setup time module",
- "type": "object",
- "properties": {}
+ "description": "setup time library"
+ }
+
+ timestamp_schema = {
+ "description": "get seconds since epoch"
}
- timestamp = {
- "description": "get the current timestamp",
- "type": "object",
- "properties": {}
+ timestampms_schema = {
+ "description": "get ms since epoch"
}
- datetime = {
- "description": "get the current datetime dict",
- "type": "object",
- "properties": {}
+ timestring_to_timestampms_schema = {
+ "description": "convert time string of the form 2017-12-05 11:07:23[.000000] to epoch timestamp (in ms)"
}
- strftime = {
- "description": "get the current formattad time",
- "type": "object",
- "properties": {
- "formating": {"type": "string"}
+ timestampms_to_timestring_schema = {
+ "description": "convert epoch timestamp in ms to time string of the form 2017-12-05 11:07:23[.000000]"
}
+
+ datetime_schema = {
+ "description": "get the current date & time as a dictionary",
}
def init(self):
pass
+ def timestampms(self):
+ return int(time.time()*1000)
+
def timestamp(self):
- return time.time()
+ return int(time.time())
+
+ def timestampms_to_timestring(self, timestampms):
+ timestamp = timestampms/1000.0
+ dt = datetime.fromtimestamp(timestamp)
+ res = dt.strftime("%Y-%m-%d %H:%M:%S.%f")
+ return res
+
+
+ def timestring_to_timestampms(self, timestr):
+ """
+ Convert time of the form "2017-12-05 11:07:23[.000000]" to epoch timestamp (in ms)
+ """
+ try:
+ if "." in timestr:
+ t = time.strptime(timestr, "%Y-%m-%d %H:%M:%S.%f")
+
+ else :
+ t = time.strptime(timestr, "%Y-%m-%d %H:%M:%S")
+ timestampms = 1000*time.mktime(t)
+ except Exception as e:
+ _log.warning("failed to convert: {}".format(e))
+ timestampms = 0
+ return timestampms
def datetime(self):
dt = datetime.datetime.now()
@@ -70,5 +98,3 @@ class Time(base_calvinlib_object.BaseCalvinlibObject):
}
return retval
- def strftime(self, formating):
- return time.strftime(formating, time.gmtime())
