#
# Utilities to handle timestamps / durations from/to integers and strings
-#
-# $Id$
-# $URL$
-#
-
#
# datetime.{datetime,timedelta} are powerful tools, but these objects are not
# natively marshalled over xmlrpc
# this is how we expose times to SQL
sql_format = "%Y-%m-%d %H:%M:%S"
sql_format_utc = "%Y-%m-%d %H:%M:%S UTC"
+
# this one (datetime.isoformat) would work too but that's less readable - we support this input though
iso_format = "%Y-%m-%dT%H:%M:%S"
# sometimes it's convenient to understand more formats
iso_format,
"%Y-%m-%d %H:%M",
"%Y-%m-%d %H:%M UTC",
+ "%Y-%m-%d %H:%M:%S.%f"
]
# for timestamps we usually accept either an int, or an ISO string,
return result
else:
raise PLCInvalidArgument, "Timestamp %r - unsupported type %r"%(input,type(input))
+
+ def utcparse(input):
+ """ Translate a string into a time using dateutil.parser.parse but make
+ sure it's in UTC time and strip the timezone, so that it's compatible
+ with normal datetime.datetime objects.
+
+ For safety this can also handle inputs that are either timestamps, or
+ datetimes
+ """
+ # prepare the input for the checks below by
+ # casting strings ('1327098335') to ints
+ if isinstance(input, StringTypes):
+ try:
+ input = int(input)
+ except ValueError:
+ pass
+
+ if isinstance (input, datetime.datetime):
+ return input
+ elif isinstance (input, StringTypes):
+ t = dateutil.parser.parse(input)
+ if t.utcoffset() is not None:
+ t = t.utcoffset() + t.replace(tzinfo=None)
+ return t
+ elif isinstance (input, (int,float,long)):
+ return datetime.datetime.fromtimestamp(input)
+ else:
+ raise
+ def string(input):
+ return datetime.datetime.strftime(Timestamp.utcparse(input), Timestamp.sql_format)
# utility for displaying durations
# be consistent in avoiding the datetime stuff