1 from types import StringTypes
6 from sfa.util.sfalogging import logger
8 DATEFORMAT = "%Y-%m-%dT%H:%M:%SZ"
11 """ Translate a string into a time using dateutil.parser.parse but make sure it's in UTC time and strip
12 the timezone, so that it's compatible with normal datetime.datetime objects.
14 For safety this can also handle inputs that are either timestamps, or datetimes
17 if isinstance (input, datetime.datetime):
18 logger.warn ("argument to utcparse already a datetime - doing nothing")
20 elif isinstance (input, StringTypes):
21 t = dateutil.parser.parse(input)
22 if t.utcoffset() is not None:
23 t = t.utcoffset() + t.replace(tzinfo=None)
25 elif isinstance (input, (int,float,long)):
26 return datetime.datetime.fromtimestamp(input)
28 logger.error("Unexpected type in utcparse [%s]"%type(input))
30 def datetime_to_string(input):
31 return datetime.datetime.strftime(input, DATEFORMAT)
33 def datetime_to_utc(input):
34 return time.gmtime(datetime_to_epoch(input))
36 def datetime_to_epoch(input):
37 return time.mktime(input.timetuple())