dos2unix
[sfa.git] / sfa / util / sfatime.py
1 #----------------------------------------------------------------------
2 # Copyright (c) 2008 Board of Trustees, Princeton University
3 #
4 # Permission is hereby granted, free of charge, to any person obtaining
5 # a copy of this software and/or hardware specification (the "Work") to
6 # deal in the Work without restriction, including without limitation the
7 # rights to use, copy, modify, merge, publish, distribute, sublicense,
8 # and/or sell copies of the Work, and to permit persons to whom the Work
9 # is furnished to do so, subject to the following conditions:
10 #
11 # The above copyright notice and this permission notice shall be
12 # included in all copies or substantial portions of the Work.
13 #
14 # THE WORK IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15 # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16 # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
17 # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
18 # HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19 # WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 # OUT OF OR IN CONNECTION WITH THE WORK OR THE USE OR OTHER DEALINGS
21 # IN THE WORK.
22 #----------------------------------------------------------------------
23 from types import StringTypes
24 import dateutil.parser
25 import datetime
26 import time
27
28 from sfa.util.sfalogging import logger
29
30 DATEFORMAT = "%Y-%m-%dT%H:%M:%SZ"
31
32 def utcparse(input):
33     """ Translate a string into a time using dateutil.parser.parse but make sure it's in UTC time and strip
34 the timezone, so that it's compatible with normal datetime.datetime objects.
35
36 For safety this can also handle inputs that are either timestamps, or datetimes
37 """
38     # prepare the input for the checks below by
39     # casting strings ('1327098335') to ints
40     if isinstance(input, StringTypes):
41         try:
42             input = int(input)
43         except ValueError:
44             pass
45
46     if isinstance (input, datetime.datetime):
47         logger.warn ("argument to utcparse already a datetime - doing nothing")
48         return input
49     elif isinstance (input, StringTypes):
50         t = dateutil.parser.parse(input)
51         if t.utcoffset() is not None:
52             t = t.utcoffset() + t.replace(tzinfo=None)
53         return t
54     elif isinstance (input, (int,float,long)):
55         return datetime.datetime.fromtimestamp(input)
56     else:
57         logger.error("Unexpected type in utcparse [%s]"%type(input))
58
59 def datetime_to_string(input):
60     return datetime.datetime.strftime(input, DATEFORMAT)
61
62 def datetime_to_utc(input):
63     return time.gmtime(datetime_to_epoch(input))
64
65 def datetime_to_epoch(input):
66     return int(time.mktime(input.timetuple()))