1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
|
'''
====================================================================
Copyright (c) 2003-2006 Barry A Scott. All rights reserved.
This software is licensed as described in the file LICENSE.txt,
which you should have received as part of this distribution.
====================================================================
'''
_debug_parse_time = 0
class DateTimeSyntaxError( Exception ):
def __init__( self, reason ):
Exception.__init__( self )
self._reason = reason
def reason( self ):
return self._reason
def __str__( self ):
return self._reason
class DateSyntaxError( DateTimeSyntaxError ):
def __init__( self, reason ):
DateTimeSyntaxError.__init__( self, reason )
class TimeSyntaxError( DateTimeSyntaxError ):
def __init__( self, reason ):
DateTimeSyntaxError.__init__( self, reason )
def parse_time( time_string ):
"""parse_time( time_string )
returns the UTC time represented by time_string
british locale defaults used
formats understood for a date are:
dayname - today, yesterday, monday, tuesday...
dd/mm/yy[yy] - numeric date
dd-mmm-yy[yy] - month as jan,feb,etc...
n units - n units of time ago
where units are:
seconds
minutes
hours
days
weeks
months
years
formats understood for time are:
HH:MM - absolute time in hours and minutes
HH:MM:SS - absolute time in hours, minutes and seconds
formats understood for data and time are:
adate atime - absolute date followed by absolute time
rdate atime - relative date followed by absolute time
atime adate - absolute time followed by absolute date
atime rdate - absolute time followed by relative date
"""
if _debug_parse_time: print '* parse_time: time_string=',time_string
date = DateConversions()
have_date = 0
have_time = 0
table = string.maketrans("-/"," ")
time_list = string.split( string.translate( time_string, table ) )
try:
day_time = convert_time( time_list[0] )
time_list = time_list[1:]
if _debug_parse_time:
print '* parse_time: Time_list[0] is a time'
except TimeSyntaxError:
try:
day_time = convert_time( time_list[-1] )
time_list = time_list[:-1]
if _debug_parse_time:
print '* parse_time: Time_list[-1] is a time'
except TimeSyntaxError:
day_time = 0
if len(time_list) == 0:
# default to today at time
result = date.midnight + day_time
if _debug_parse_time: print '* parse_time: 1 return',format_time(result)
return result
match_type = date.numeric_type
matches = []
for word in time_list:
day_matches = date.findMatchingDateName( word )
if len(day_matches) == 0:
raise DateSyntaxError, "%s unknown date word" % word
if date.isAmbiguous( day_matches ):
raise DateSyntaxError, date.reportAmbiguity( word, day_matches )
this_type = date.typeOfMatch( day_matches )
if this_type != date.numeric_type:
if match_type == date.numeric_type:
match_type = this_type
elif match_type != this_type:
raise DateSyntaxError, "ambiguous mix of unit and month names"
matches.append( day_matches[0] )
if _debug_parse_time: print '* parse_time: matches=',matches
if match_type == date.day_type:
if len(matches) != 1:
raise DateSyntaxError, "too many day words"
day_matches = matches[0]
result = date.convertDay( day_matches[2] ) + day_time
if _debug_parse_time: print '* parse_time: 2 return',format_time(result)
return result
if match_type == date.unit_type:
# expect a set of pair of <num> <unit>
if _debug_parse_time >= 2:
print 'matches',matches
if (len(matches)&1) == 1:
raise DateSyntaxError, 'must have an even number parameters when using time units'
time_offset = 0
for index in range( 0, len(matches), 2 ):
value_tuple = matches[index]
unit_tuple = matches[index+1]
if value_tuple[1] != date.numeric_type:
raise DateSyntaxError, 'Expecting a number of units'
if unit_tuple[1] != date.unit_type:
raise DateSyntaxError, 'Expecting a unit name'
value = value_tuple[2]
unit = unit_tuple[2]
time_offset = time_offset + value*unit
result = date.now - time_offset
if _debug_parse_time: print '* parse_time: 3 return',format_time(result)
return result
if match_type == date.month_type:
# absolute date
if len(matches) < 1 or len(matches) > 3:
raise DateSyntaxError, 'too many date parts'
day = -1
month = -1
year = -1
num_month_types = 0
for entry in matches:
if date.isMonth( entry ):
num_month_types = num_month_types + 1
if num_month_types != 1:
raise DateSyntaxError,'too many months in the date string'
if date.isMonth( matches[0] ):
month = matches[0][2]
day = matches[1][2]
if len(matches) == 3:
year = matches[2][2]
else:
day = matches[0][2]
if matches[1][1] != date.month_type:
raise DateSyntaxError,'expecting month as first or second part of date'
month = matches[1][2]
if len(matches) == 3:
year = matches[2][2]
seconds = day_time%60
minutes = (day_time/60)%60
hours = day_time/60/60
result = date.absDate( day, month, year, hours, minutes, seconds )
if _debug_parse_time: print '* parse_time: 4 return',format_time(result)
return result
if match_type == date.numeric_type and len(matches) == 3:
# assume its in locale order - which is assumed to be D M Y
day = matches[0][2]
month = matches[1][2]
year = matches[2][2]
seconds = day_time%60
minutes = (day_time/60)%60
hours = day_time/60/60
result = date.absDate( day, month, year, hours, minutes, seconds )
if _debug_parse_time: print '* parse_time: 4 return',format_time(result)
return result
raise DateSyntaxError,'cannot understand date and time string ' + time_string
def convert_time( time_str ):
time_list = string.split( time_str, ':' )
if len(time_list) < 2:
# not a time - no ":"
raise TimeSyntaxError, "Not a time"
if len(time_list) > 3:
raise TimeSyntaxError, "Too many time parts"
hour = time_list[0]
minute = time_list[1]
second = '0'
if len(time_list) > 2:
second = time_list[2]
try:
hour = string.atoi( hour )
minute = string.atoi( minute )
second = string.atoi( second )
except:
return -1
if( hour < 0 or hour > 23 ):
raise TimeSyntaxError, "hour value of %d invalid" % hour
if( minute < 0 or minute > 59 ):
raise TimeSyntaxError, "minutes value of %d invalid" % hour
if( second < 0 or second > 59 ):
raise TimeSyntaxError, "seconds value of %d invalid" % hour
day_time = (hour*60 + minute)*60 + second
return day_time
class DateConversions:
seconds_in_one_day = 24*60*60
day_type = 1
month_type = 2
unit_type = 3
numeric_type = 4
date_names = [
# day names
('today', day_type, 0),
('yesterday', day_type, -1),
('monday', day_type, 1),
('tuesday', day_type, 2),
('wednesday', day_type, 3),
('thursday', day_type, 4),
('friday', day_type, 5),
('saturday', day_type, 6),
('sunday', day_type, 7),
# month names
('january', month_type, 1),
('feburary', month_type, 2),
('march', month_type, 3),
('april', month_type, 4),
('may', month_type, 5),
('june', month_type, 6),
('july', month_type, 7),
('august', month_type, 8),
('september', month_type, 9),
('october', month_type, 10),
('november', month_type, 11),
('december', month_type, 12),
# unit names
('seconds', unit_type, 1),
('minutes', unit_type, 60),
('hours', unit_type, 60*60),
('days', unit_type, 24*60*60.),
('weeks', unit_type, 7*24*60*60),
('months', unit_type, 30*24*60*60),
('years', unit_type, 365*24*60*60)
]
def __init__( self ):
self.now = time.time()
self.year, self.month, self.day, self.hour, self.minute, self.second, self.weekday, self.julian, self.dst = time.localtime( self.now )
self.midnight = time.mktime(
(self.year, self.month, self.day,
0, 0, 0,
self.weekday, self.julian, self.dst) )
def convertDay( self, day_offset ):
if day_offset == 0: # today
return self.midnight
elif day_offset == -1: # yesterday
return self.midnight - self.seconds_in_one_day
else:
# day of week
offset = day_offset - self.weekday - 1
# make sure its in the past
if offset >= 0:
offset = offset - 7
return self.midnight + offset*self.seconds_in_one_day
def absDate( self, day, month, year, hour=0, minute=0, second=0 ):
future_check = 0
if year < 0:
year = self.year
future_check = 1
elif year < 70:
year = year + 2000
elif year < 100:
year = year + 1900
try:
date = time.mktime(
(year, month, day,
hour, minute, second,
self.weekday, self.julian, -1) )
except OverflowError:
raise DateSyntaxError,'cannot convert date and time year=%d/month=%d/day=%d %d:%d:%d' % (
year, month, day, hour, minute, second )
if date > self.now and future_check:
year = year - 1
try:
date = time.mktime(
(year, month, day,
hour, minute, second,
self.weekday, self.julian, -1) )
except OverflowError:
raise DateSyntaxError,'cannot convert date and time %d/%d/%d %d:%d:%d' % (
year, month, day, hour, minute, second )
return date
def findMatchingDateName( self, name ):
try:
value = string.atoi( name )
return [(name, self.numeric_type, value )]
except:
pass
matches = []
name_len = len(name)
for entry in self.date_names:
entry_name = entry[0]
if len(entry_name) >= name_len and entry_name[0:name_len] == name:
matches.append( entry )
return matches
def typeOfMatch( self, matches ):
return matches[0][1]
def isAmbiguous( self, matches ):
return len(matches) > 1
def isDay( self, matches ):
return matches[1] == self.day_type
def isMonth( self, matches ):
return matches[1] == self.month_type
def isUnit( self, matches ):
return matches[1] == self.unit_type
def isNumeric( self, matches ):
return matches[1] == self.numeric_type
def reportAmbiguity( self, name, tuples ):
names = map( lambda t: t[0], tuples )
return "%s is ambiguous, it matches: %s" % (name, string.join( names, ', ' ))
|