Package amplee :: Package utils :: Module isodate
[hide private]
[frames] | no frames]

Source Code for Module amplee.utils.isodate

  1  #!/usr/bin/env python 
  2   
  3  """ 
  4  isodate.py 
  5   
  6  Functions for manipulating a subset of ISO8601 date, as specified by 
  7    <http://www.w3.org/TR/NOTE-datetime> 
  8     
  9  Exposes: 
 10    - parse(s) 
 11      s being a conforming (regular or unicode) string. Raises ValueError for 
 12      invalid strings. Returns a float (representing seconds from the epoch;  
 13      see the time module). 
 14       
 15    - parse_datetime(s)   # if datetime module is available 
 16      s being a conforming (regular or unicode) string. Raises ValueError for 
 17      invalid strings. Returns a datetime instance. 
 18       
 19    - asString(i) 
 20      i being an integer or float. Returns a conforming string. 
 21     
 22  TODO: 
 23    - Precision? it would be nice to have an interface that tells us how 
 24      precise a datestring is, so that we don't make assumptions about it;  
 25      e.g., 2001 != 2001-01-01T00:00:00Z. 
 26   
 27  Thanks to Andrew Dalke for datetime support. 
 28  """ 
 29   
 30  __license__ = """ 
 31  Copyright (c) 2002-2005 Mark Nottingham <mnot@pobox.com> 
 32   
 33  Permission is hereby granted, free of charge, to any person obtaining a copy 
 34  of this software and associated documentation files (the "Software"), to deal 
 35  in the Software without restriction, including without limitation the rights 
 36  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 
 37  copies of the Software, and to permit persons to whom the Software is 
 38  furnished to do so, subject to the following conditions: 
 39   
 40  The above copyright notice and this permission notice shall be included in all 
 41  copies or substantial portions of the Software. 
 42   
 43  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 
 44  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 
 45  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 
 46  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 
 47  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 
 48  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 
 49  SOFTWARE. 
 50   
 51  Note: datetime support added by Andrew Dalke <dalke@dalkescientific.com>. 
 52  All copyrightable changes by Andrew Dalke are released into the public domain.   
 53  No copyright protection is asserted. 
 54  """ 
 55   
 56   
 57  import sys, time, re, operator 
 58  from types import IntType, FloatType 
 59  from calendar import timegm 
 60   
 61  try: 
 62      import datetime 
 63  except ImportError: 
 64      _has_datetime = 0 
 65  else: 
 66      _has_datetime = 1 
 67   
 68   
 69  __version__ = "0.7" 
 70   
 71  date_parser = re.compile(r"""^ 
 72      (?P<year>\d{4,4}) 
 73      (?: 
 74          - 
 75          (?P<month>\d{1,2}) 
 76          (?: 
 77              - 
 78              (?P<day>\d{1,2}) 
 79              (?: 
 80                  T 
 81                  (?P<hour>\d{1,2}) 
 82                  : 
 83                  (?P<minute>\d{1,2}) 
 84                  (?: 
 85                      : 
 86                      (?P<second>\d{1,2}) 
 87                      (?: 
 88                          \. 
 89                          (?P<dec_second>\d+)? 
 90                      )? 
 91                  )?                     
 92                  (?: 
 93                      Z 
 94                      | 
 95                      (?: 
 96                          (?P<tz_sign>[+-]) 
 97                          (?P<tz_hour>\d{1,2}) 
 98                          : 
 99                          (?P<tz_min>\d{2,2}) 
100                      ) 
101                  ) 
102              )? 
103          )? 
104      )? 
105  $""", re.VERBOSE) 
106   
107   
108 -def parse(s):
109 """ parse a string and return seconds since the epoch. """ 110 assert isinstance(s, basestring) 111 r = date_parser.search(s) 112 try: 113 a = r.groupdict('0') 114 except: 115 raise ValueError, 'invalid date string format' 116 d = timegm(( int(a['year']), 117 int(a['month']) or 1, 118 int(a['day']) or 1, 119 int(a['hour']), 120 int(a['minute']), 121 int(a['second']), 122 0, 123 0, 124 0 125 )) 126 return d - int("%s%s" % ( 127 a.get('tz_sign', '+'), 128 ( int(a.get('tz_hour', 0)) * 60 * 60 ) + \ 129 ( int(a.get('tz_min', 0)) * 60 )) 130 )
131 132 if _has_datetime:
133 - def parse_datetime(s):
134 """ parse a string and return a datetime object. """ 135 assert isinstance(s, basestring) 136 r = date_parser.search(s) 137 try: 138 a = r.groupdict('0') 139 except: 140 raise ValueError, 'invalid date string format' 141 142 dt = datetime.datetime(int(a['year']), 143 int(a['month']) or 1, 144 int(a['day']) or 1, 145 # If not given these will default to 00:00:00.0 146 int(a['hour']), 147 int(a['minute']), 148 int(a['second']), 149 # Convert into microseconds 150 int(a['dec_second'])*100000, 151 ) 152 tz_hours_offset = int(a['tz_hour']) 153 tz_mins_offset = int(a['tz_min']) 154 if a.get('tz_sign', '+') == "-": 155 return dt + datetime.timedelta(hours = tz_hours_offset, 156 minutes = tz_mins_offset) 157 else: 158 return dt - datetime.timedelta(hours = tz_hours_offset, 159 minutes = tz_mins_offset)
160
161 -def asString(i):
162 """ given seconds since the epoch, return a dateTime string. """ 163 assert type(i) in [IntType, FloatType] 164 year, month, day, hour, minute, second, wday, jday, dst = time.gmtime(i) 165 o = str(year) 166 if (month, day, hour, minute, second) == (1, 1, 0, 0, 0): return o 167 o = o + '-%2.2d' % month 168 if (day, hour, minute, second) == (1, 0, 0, 0): return o 169 o = o + '-%2.2d' % day 170 if (hour, minute, second) == (0, 0, 0): return o 171 o = o + 'T%2.2d:%2.2d' % (hour, minute) 172 if second != 0: 173 o = o + ':%2.2d' % second 174 o = o + 'Z' 175 return o
176 177
178 -def _cross_test():
179 for iso in ("1997-07-16T19:20+01:00", 180 "2001-12-15T22:43:46Z", 181 "2004-09-26T21:10:15Z", 182 "2004", 183 "2005-04", 184 "2005-04-30", 185 "2004-09-26T21:10:15.1Z", 186 "2004-09-26T21:10:15.1+05:00", 187 "2004-09-26T21:10:15.1-05:00", 188 ): 189 timestamp = parse(iso) 190 dt1 = datetime.datetime.utcfromtimestamp(timestamp) 191 dt2 = parse_datetime(iso) 192 if (dt1 != dt2 and 193 dt1 != dt2.replace(microsecond=0)): 194 raise AssertionError("Different: %r != %r" % 195 (dt1, dt2))
196 197 if __name__ == "__main__": 198 print parse("1997-07-16T19:20+01:00") 199 print parse("2001-12-15T22:43:46Z") 200 print parse("2004-09-26T21:10:15Z") 201 if _has_datetime: 202 _cross_test() 203 print parse_datetime("1997-07-16T19:20+01:00") 204 print parse_datetime("2001-12-15T22:43:46Z") 205 print parse_datetime("2004-09-26T21:10:15Z") 206