Project

General

Profile

« Previous | Next » 

Revision 1365

dates.py: Added parse_date_range() and helper funcs could_be_year() and could_be_day()

View differences:

lib/dates.py
2 2

  
3 3
import datetime
4 4
import dateutil.tz
5
import strings
5 6
import time
6 7

  
7 8
utc = dateutil.tz.tzutc()
......
39 40
def strtotime(str_, default=epoch):
40 41
    import dateutil.parser
41 42
    return dateutil.parser.parse(str_, default=default)
43

  
44
def could_be_year(str_): return str_.isdigit() and len(str_) == 4
45

  
46
def could_be_day(str_): return str_.isdigit() and len(str_) <= 2
47

  
48
def parse_date_range(str_, range_sep='-', part_sep=' '):
49
    str_ = strings.single_space(str_)
50
    # range_sep might be used as date part separator instead
51
    if str_.find(part_sep) < 0: return (str_, None)
52
    
53
    start, sep, end = str_.partition(range_sep)
54
    if sep == '': return (str_, None) # not a range
55
    start = start.split(part_sep)
56
    end = end.split(part_sep)
57
    
58
    # Has form M D1-D2 or M D1-D2 Y (not M1 Y1-M2 Y2 or M1 D1-M2 D2)
59
    if len(start) == 2 and (len(end) == 1 or (
60
            len(end) == 2 and could_be_day(start[-1]) and could_be_day(end[0])
61
            and could_be_year(end[-1])
62
        )):
63
        end.insert(0, start[0]) # make end fully specified
64
    ct_diff = len(end) - len(start)
65
    # Has form D1-D2 M Y, M1 D1-M2 D2 Y, M1-M2 Y, etc.
66
    if ct_diff > 0: start += end[-ct_diff:] # make start fully specified
67
    # Other forms are invalid and will be left as-is
68
    
69
    return (start, end)

Also available in: Unified diff