1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18 r"""parsedate.py: Parse date strings.
19
20 """
21 __docformat__ = "restructuredtext en"
22
23 import datetime
24 import re
25
26 yyyymmdd_re = re.compile(r'(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})$')
27 yyyy_mm_dd_re = re.compile(r'(?P<year>[0-9]{4})([-/.])(?P<month>[0-9]{2})\2(?P<day>[0-9]{2})$')
28
30 """Parse a string into a date.
31
32 If the value supplied is already a date-like object (ie, has 'year',
33 'month' and 'day' attributes), it is returned without processing.
34
35 Supported date formats are:
36
37 - YYYYMMDD
38 - YYYY-MM-DD
39 - YYYY/MM/DD
40 - YYYY.MM.DD
41
42 """
43 if (hasattr(value, 'year')
44 and hasattr(value, 'month')
45 and hasattr(value, 'day')):
46 return value
47
48 mg = yyyymmdd_re.match(value)
49 if mg is None:
50 mg = yyyy_mm_dd_re.match(value)
51
52 if mg is not None:
53 year, month, day = (int(i) for i in mg.group('year', 'month', 'day'))
54 return datetime.date(year, month, day)
55
56 raise ValueError('Unrecognised date format')
57