add support for migrations with sqlalchemy-migrate
[sfa.git] / sfa / util / sfatime.py
1 from types import StringTypes
2 import dateutil.parser
3 import datetime
4 import time
5
6 from sfa.util.sfalogging import logger
7
8 DATEFORMAT = "%Y-%m-%dT%H:%M:%SZ"
9
10 def utcparse(input):
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.
13
14 For safety this can also handle inputs that are either timestamps, or datetimes
15 """
16     # perpare the input for the checks below by
17     # casting strings ('1327098335') to ints
18     if isinstance(input, StringTypes):
19         try:
20             input = int(input)
21         except ValueError:
22             pass
23           
24     if isinstance (input, datetime.datetime):
25         logger.warn ("argument to utcparse already a datetime - doing nothing")
26         return input
27     elif isinstance (input, StringTypes):
28         t = dateutil.parser.parse(input)
29         if t.utcoffset() is not None:
30             t = t.utcoffset() + t.replace(tzinfo=None)
31         return t
32     elif isinstance (input, (int,float,long)):
33         return datetime.datetime.fromtimestamp(input)
34     else:
35         logger.error("Unexpected type in utcparse [%s]"%type(input))
36
37 def datetime_to_string(input):
38     return datetime.datetime.strftime(input, DATEFORMAT)
39
40 def datetime_to_utc(input):
41     return time.gmtime(datetime_to_epoch(input))    
42
43 def datetime_to_epoch(input):
44     return int(time.mktime(input.timetuple()))
45
46
47