X-Git-Url: http://git.onelab.eu/?a=blobdiff_plain;f=sfa%2Futil%2Fsfatime.py;h=34f4dce9a9fba783d1d75daef76de954c9ca9263;hb=b059733ab0c8d4d43acb8530dceda41e90715af5;hp=11cc566b33d11359e164c7a4590d5999635b0472;hpb=b2d3e37b8c36a60f2449c235e0b4f7d2942e3292;p=sfa.git diff --git a/sfa/util/sfatime.py b/sfa/util/sfatime.py index 11cc566b..34f4dce9 100644 --- a/sfa/util/sfatime.py +++ b/sfa/util/sfatime.py @@ -1,16 +1,26 @@ from types import StringTypes import dateutil.parser import datetime +import time from sfa.util.sfalogging import logger +DATEFORMAT = "%Y-%m-%dT%H:%M:%SZ" + 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 """ - + # perpare 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): logger.warn ("argument to utcparse already a datetime - doing nothing") return input @@ -19,8 +29,19 @@ For safety this can also handle inputs that are either timestamps, or datetimes if t.utcoffset() is not None: t = t.utcoffset() + t.replace(tzinfo=None) return t - elif isinstance (input, (int,float)): + elif isinstance (input, (int,float,long)): return datetime.datetime.fromtimestamp(input) else: logger.error("Unexpected type in utcparse [%s]"%type(input)) +def datetime_to_string(input): + return datetime.datetime.strftime(input, DATEFORMAT) + +def datetime_to_utc(input): + return time.gmtime(datetime_to_epoch(input)) + +def datetime_to_epoch(input): + return int(time.mktime(input.timetuple())) + + +