Back to index

moin  1.9.0~rc2
parsedate.py
Go to the documentation of this file.
00001 #!/usr/bin/env python
00002 #
00003 # Copyright (C) 2007 Lemur Consulting Ltd
00004 #
00005 # This program is free software; you can redistribute it and/or modify
00006 # it under the terms of the GNU General Public License as published by
00007 # the Free Software Foundation; either version 2 of the License, or
00008 # (at your option) any later version.
00009 #
00010 # This program is distributed in the hope that it will be useful,
00011 # but WITHOUT ANY WARRANTY; without even the implied warranty of
00012 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013 # GNU General Public License for more details.
00014 # 
00015 # You should have received a copy of the GNU General Public License along
00016 # with this program; if not, write to the Free Software Foundation, Inc.,
00017 # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
00018 r"""parsedate.py: Parse date strings.
00019 
00020 """
00021 __docformat__ = "restructuredtext en"
00022 
00023 import datetime
00024 import re
00025 
00026 yyyymmdd_re = re.compile(r'(?P<year>[0-9]{4})(?P<month>[0-9]{2})(?P<day>[0-9]{2})$')
00027 yyyy_mm_dd_re = re.compile(r'(?P<year>[0-9]{4})([-/.])(?P<month>[0-9]{2})\2(?P<day>[0-9]{2})$')
00028 
00029 def date_from_string(value):
00030     """Parse a string into a date.
00031 
00032     If the value supplied is already a date-like object (ie, has 'year',
00033     'month' and 'day' attributes), it is returned without processing.
00034 
00035     Supported date formats are:
00036 
00037      - YYYYMMDD
00038      - YYYY-MM-DD 
00039      - YYYY/MM/DD 
00040      - YYYY.MM.DD 
00041 
00042     """
00043     if (hasattr(value, 'year')
00044         and hasattr(value, 'month')
00045         and hasattr(value, 'day')):
00046         return value
00047 
00048     mg = yyyymmdd_re.match(value)
00049     if mg is None:
00050         mg = yyyy_mm_dd_re.match(value)
00051 
00052     if mg is not None:
00053         year, month, day = (int(i) for i in mg.group('year', 'month', 'day'))
00054         return datetime.date(year, month, day)
00055 
00056     raise ValueError('Unrecognised date format')