substantial cleanup of the renew method and client
[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 import re
28
29 from sfa.util.sfalogging import logger
30
31 SFATIME_FORMAT = "%Y-%m-%dT%H:%M:%SZ"
32
33 def utcparse(input):
34     """ Translate a string into a time using dateutil.parser.parse but make sure it's in UTC time and strip
35 the timezone, so that it's compatible with normal datetime.datetime objects.
36
37 For safety this can also handle inputs that are either timestamps, or datetimes
38 """
39
40     def handle_shorthands (input):
41         """recognize string like +5d or +3w or +2m as 
42         2 days, 3 weeks or 2 months from now"""
43         if input.startswith('+'):
44             match=re.match (r"([0-9]+)([dwm])",input[1:])
45             if match:
46                 how_many=int(match.group(1))
47                 what=match.group(2)
48                 if what == 'd':         d=datetime.timedelta(days=how_many)
49                 elif what == 'w':       d=datetime.timedelta(weeks=how_many)
50                 elif what == 'm':       d=datetime.timedelta(weeks=4*how_many)
51                 return datetime.datetime.utcnow()+d
52
53     # prepare the input for the checks below by
54     # casting strings ('1327098335') to ints
55     if isinstance(input, StringTypes):
56         try:
57             input = int(input)
58         except ValueError:
59             try:
60                 new_input=handle_shorthands(input)
61                 if new_input is not None: input=new_input
62             except:
63                 import traceback
64                 traceback.print_exc()
65
66     #################### here we go
67     if isinstance (input, datetime.datetime):
68         #logger.info ("argument to utcparse already a datetime - doing nothing")
69         return input
70     elif isinstance (input, StringTypes):
71         t = dateutil.parser.parse(input)
72         if t.utcoffset() is not None:
73             t = t.utcoffset() + t.replace(tzinfo=None)
74         return t
75     elif isinstance (input, (int,float,long)):
76         return datetime.datetime.fromtimestamp(input)
77     else:
78         logger.error("Unexpected type in utcparse [%s]"%type(input))
79
80 def datetime_to_string(input):
81     return datetime.datetime.strftime(input, SFATIME_FORMAT)
82
83 def datetime_to_utc(input):
84     return time.gmtime(datetime_to_epoch(input))
85
86 def datetime_to_epoch(input):
87     return int(time.mktime(input.timetuple()))
88
89 def add_datetime(input, days=0, hours=0, minutes=0, seconds=0):
90     """
91     Adjust the input date by the specified delta (in seconds).
92     """
93     dt = utcparse(input)
94     return dt + datetime.timedelta(days=days, hours=hours, minutes=minutes, seconds=seconds)
95
96 if __name__ == '__main__':
97     for input in [
98             '+2d',
99             '+3w',
100             '+2m',
101             1401282977.575632,
102             1401282977,
103             '1401282977',
104             '2014-05-28',
105             '2014-05-28T15:18',
106             '2014-05-28T15:18:30',
107     ]:
108         print "input=%20s -> parsed %s"%(input,datetime_to_string(utcparse(input)))