even safer handling of expiration types across
[sfa.git] / sfa / util / sfatime.py
1 from types import StringTypes
2 import dateutil.parser
3 import datetime
4
5 from sfa.util.sfalogging import logger
6
7 def utcparse(input):
8     """ Translate a string into a time using dateutil.parser.parse but make sure it's in UTC time and strip
9 the timezone, so that it's compatible with normal datetime.datetime objects.
10
11 For safety this can also handle inputs that are either timestamps, or datetimes
12 """
13     
14     if isinstance (input, datetime.datetime):
15         logger.warn ("argument to utcparse already a datetime - doing nothing")
16         return input
17     elif isinstance (input, StringTypes):
18         t = dateutil.parser.parse(input)
19         if t.utcoffset() is not None:
20             t = t.utcoffset() + t.replace(tzinfo=None)
21         return t
22     elif isinstance (input, (int,float)):
23         return datetime.datetime.fromtimestamp(input)
24     else:
25         logger.error("Unexpected type in utcparse [%s]"%type(input))
26