<s> import datetime <EOL> import re <EOL> from dateutil . parser import parse <EOL> from dateutil . relativedelta import relativedelta <EOL> try : <EOL> basestring = basestring <EOL> except NameError : <EOL> basestring = str <EOL> def serialize ( value ) : <EOL> if isinstance ( value , datetime . date ) : <EOL> return value . isoformat ( ) <EOL> else : <EOL> return value <EOL> def extract ( obj ) : <EOL> if isinstance ( obj , datetime . date ) : <EOL> if hasattr ( obj , '<STR_LIT:date>' ) : <EOL> return obj . date ( ) <EOL> else : <EOL> return obj <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" . format ( obj ) ) <EOL> def parse_description ( s ) : <EOL> today = datetime . date . today ( ) <EOL> if s == '<STR_LIT>' : <EOL> return today <EOL> elif s == '<STR_LIT>' : <EOL> return today - relativedelta ( days = <NUM_LIT:1> ) <EOL> else : <EOL> match = re . match ( '<STR_LIT>' , s ) <EOL> if match : <EOL> return today - relativedelta ( days = int ( match . group ( <NUM_LIT:1> ) ) ) <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> def normalize ( obj ) : <EOL> if obj == None : <EOL> return None <EOL> elif isinstance ( obj , datetime . date ) : <EOL> return extract ( obj ) <EOL> elif isinstance ( obj , basestring ) : <EOL> try : <EOL> return extract ( parse ( obj ) ) <EOL> except ValueError : <EOL> try : <EOL> return extract ( parse_description ( obj ) ) <EOL> except ValueError : <EOL> raise ValueError ( "<STR_LIT>" + obj ) <EOL> else : <EOL> raise ValueError ( "<STR_LIT>" ) <EOL> def range ( start = None , stop = None , months = <NUM_LIT:0> , days = <NUM_LIT:0> ) : <EOL> yesterday = datetime . date . today ( ) - relativedelta ( days = <NUM_LIT:1> ) <EOL> start = normalize ( start ) or yesterday <EOL> stop = normalize ( stop ) <EOL> is_past = days < <NUM_LIT:0> or months < <NUM_LIT:0> <EOL> if days or months : <EOL> if start and stop : <EOL> raise Exception ( <EOL> "<STR_LIT>" ) <EOL> else : <EOL> if is_past : <EOL> days = days + <NUM_LIT:1> <EOL> else : <EOL> days = days - <NUM_LIT:1> <EOL> delta = relativedelta ( days = days , months = months ) <EOL> stop = start + delta <EOL> stop = stop or start <EOL> return map ( serialize , sorted ( ( start , stop ) ) ) <EOL> def is_relative ( datestring ) : <EOL> return not '<STR_LIT:->' in datestring </s>
