Web   ·   Wiki   ·   Activities   ·   Blog   ·   Lists   ·   Chat   ·   Meeting   ·   Bugs   ·   Git   ·   Translate   ·   Archive   ·   People   ·   Donate
summaryrefslogtreecommitdiffstats
path: root/secore/parsedate.py
blob: 684d5f25d382eee32fcde8894e607682c090e3db (plain)
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
#!/usr/bin/env python
#
# Copyright (C) 2007 Lemur Consulting Ltd
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
# 
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
r"""parsedate.py: Parse date strings.

"""
__docformat__ = "restructuredtext en"

import datetime
import re

yyyymmdd_re = re.compile(r'(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})$')
yyyy_mm_dd_re = re.compile(r'(?P<year>[0-9]{4})([-/.])(?P<month>[0-9]{2})\2(?P<day>[0-9]{2})$')

def date_from_string(value):
    """Parse a string into a date.

    If the value supplied is already a date-like object (ie, has 'year',
    'month' and 'day' attributes), it is returned without processing.

    Supported date formats are:

     - YYYYMMDD
     - YYYY-MM-DD 
     - YYYY/MM/DD 
     - YYYY.MM.DD 

    """
    if (hasattr(value, 'year')
        and hasattr(value, 'month')
        and hasattr(value, 'day')):
        return value

    mg = yyyymmdd_re.match(value)
    if mg is None:
        mg = yyyy_mm_dd_re.match(value)

    if mg is not None:
        year, month, day = (int(i) for i in mg.group('year', 'month', 'day'))
        return datetime.date(year, month, day)

    raise ValueError('Unrecognised date format')