Imported Upstream version 0.48
[platform/upstream/libical.git] / src / python / Time.py
1 #!/usr/bin/env python 
2 # -*- Mode: python -*-
3 #======================================================================
4 # FILE: Time.py
5 # CREATOR: eric 
6 #
7 # DESCRIPTION:
8 #   
9 #
10 #  $Id: Time.py,v 1.3 2002-07-12 08:02:46 acampi Exp $
11 #  $Locker:  $
12 #
13 # (C) COPYRIGHT 2001, Eric Busboom <eric@softwarestudio.org>
14 # (C) COPYRIGHT 2001, Patrick Lewis <plewis@inetarena.com>  
15 #
16 # This program is free software; you can redistribute it and/or modify
17 # it under the terms of either: 
18 #
19 #    The LGPL as published by the Free Software Foundation, version
20 #    2.1, available at: http://www.fsf.org/copyleft/lesser.html
21 #
22 #  Or:
23 #
24 #    The Mozilla Public License Version 1.0. You may obtain a copy of
25 #    the License at http://www.mozilla.org/MPL/
26 #======================================================================
27
28 from LibicalWrap import *
29 from Property import Property
30 from types import DictType, StringType, IntType, FloatType
31 from Duration import Duration
32
33 UTC = icaltimezone_get_utc_timezone()
34
35 class Time(Property):
36     """ Represent iCalendar DATE, TIME and DATE-TIME """
37     def __init__(self, arg, name="DTSTART", zone=None):
38         """ 
39         Create a new Time from a string or number of seconds past the 
40         POSIX epoch
41
42         Time("19970325T123000Z")  Construct from an iCalendar string
43         Time(8349873494)          Construct from seconds past POSIX epoch
44         
45         """
46         e1=icalerror_supress("MALFORMEDDATA")
47         e2=icalerror_supress("BADARG")
48
49         if isinstance(arg, DictType):
50             # Dictionary -- used for creating from Component
51             self.tt = icaltime_from_string(arg['value'])
52             Property.__init__(self, ref=arg['ref'])
53         else:
54             if isinstance(arg, StringType):
55                 # Create from an iCal string
56                 self.tt = icaltime_from_string(arg)
57             elif isinstance(arg, IntType) or   \
58                  isinstance(arg, FloatType): 
59                 # Create from seconds past the POSIX epoch
60                 if zone:
61                         self.tt = icaltime_from_timet_with_zone(int(arg),0,icaltimezone_get_builtin_timezone(zone))
62                 else:
63                         self.tt = icaltime_from_timet_with_zone(int(arg),0,icaltimezone_get_utc_timezone())
64             elif isinstance(arg, Time):
65                 # Copy an instance
66                 self.tt = arg.tt
67             else:
68                 self.tt = icaltime_null_time()
69
70             Property.__init__(self,type=name)
71
72         icalerror_restore("MALFORMEDDATA",e1)
73         icalerror_restore("BADARG",e2)
74
75         if icaltime_is_null_time(self.tt):
76             raise Property.ConstructorFailedError("Failed to construct a Time")
77
78         try:
79             self._update_value()
80         except Property.UpdateFailedError:
81             raise Property.ConstructorFailedError("Failed to construct a Time")
82
83     def _update_value(self):
84         self.normalize()
85         self.value(icaltime_as_ical_string(self.tt),"DATE-TIME")
86
87     def valid(self):
88         " Return true if this is a valid time "
89         return not icaltime_is_null_time(self.tt)
90
91     def utc_seconds(self,v=None):
92         """ Return or set time in seconds past POSIX epoch"""
93         tz = icaltimezone_get_builtin_timezone(self.timezone())
94         if (v!=None):
95             self.tt = icaltime_from_timet_with_zone(v,0,tz)
96             self._update_value()
97
98         return icaltime_as_timet_with_zone(self.tt, tz)
99
100     def is_utc(self):
101         """ Return a boolean indicating if time is in UTC """
102         return icaltime_is_utc(self.tt)
103
104     def is_date(self):
105         """ Return a boolean indicating if time is actually a date """
106         return icaltime_is_date(self.tt)
107
108     def timezone(self,v=None):
109         """ Return, set (if none) or alter the timezone for this time """
110         
111         origtz = icaltime_get_tzid(self.tt)
112
113         if (v != None):
114             assert(isinstance(v,StringType) )
115             if (v == "UTC"):
116                 tz = icaltimezone_get_utc_timezone()
117                 del self['TZID']
118             else:
119                 tz = icaltimezone_get_builtin_timezone(v)
120
121             if not origtz:
122                 self.tt = icaltime_set_timezone(self.tt, tz)
123             else:
124                 self.tt = icaltime_convert_to_zone(self.tt,tz)
125
126             if (icaltime_get_tzid(self.tt) != "UTC"):
127                 self['TZID'] = icaltime_get_tzid(self.tt)
128
129         self._update_value()
130         return icaltime_get_tzid(self.tt)
131
132     def normalize(self):
133         self.tt = icaltime_normalize(self.tt)
134
135     def __second_property(self,v=None):
136         """ Get or set the seconds component of this time """
137         if(v != None):
138             self.tt.second = v
139             self._update_value()
140         return self.tt.second
141     second = property(__second_property, __second_property)
142
143     def __minute_property(self,v=None):
144         """ Get or set the minute component of this time """
145         if(v != None):
146             self.tt.minute = v
147             self._update_value()
148         return self.tt.minute
149     minute = property(__minute_property, __minute_property)
150
151     def __hour_property(self,v=None):
152         """ Get or set the hour component of this time """
153         if(v != None):
154             self.tt.hour = v
155             self._update_value()
156         return self.tt.hour
157     hour = property(__hour_property, __hour_property)
158
159     def __day_property(self,v=None):
160         """ Get or set the month day component of this time """
161         if(v != None):
162             self.tt.day = v
163             self._update_value()
164         return self.tt.day
165     day = property(__day_property, __day_property)
166
167     def __month_property(self,v=None):
168         """ Get or set the month component of this time. January is month 1 """
169         if(v != None):
170             self.tt.month = v
171             self._update_value()
172         return self.tt.month
173     month = property(__month_property, __month_property)
174
175     def __year_property(self,v=None):
176         """ Get or set the year component of this time """
177         if(v != None):
178             self.tt.year = v
179             self._update_value()
180         return self.tt.year
181     year = property(__year_property, __year_property)
182
183
184     def __cmp__(self,other):
185
186         if other == None:
187             return cmp(self.utc_seconds(),None)
188
189         return cmp(self.utc_seconds(),other.utc_seconds())
190
191
192     def __add__(self,o):
193
194         other = Duration(o,"DURATION")      
195
196         if not other.valid():
197             return Duration(0,"DURATION")
198
199         print self.utc_seconds(), other.seconds()
200         seconds = self.utc_seconds() + other.seconds()
201
202         new = Time(seconds,self.name(),self.timezone())
203
204         return new
205
206     def __radd_(self,o):
207         return self.__add__(o)
208     
209
210     def __sub__(self,o):
211
212         
213         if isinstance(o,Time):
214             # Subtract a time from this time and return a duration
215             seconds = self.utc_seconds() - other.utc_seconds()
216             return Duration(seconds)
217         elif isinstance(o,Duration):
218             # Subtract a duration from this time and return a time
219             other = Duration(o)
220             if(not other.valid()):
221                 return Time()
222
223             seconds = self.utc_seconds() - other.seconds()
224             return Time(seconds)
225         else:
226             raise TypeError, "subtraction with Time reqires Time or Duration"