#!/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[0-9]{4})(?P[0-9]{2})(?P[0-9]{2})$') yyyy_mm_dd_re = re.compile(r'(?P[0-9]{4})([-/.])(?P[0-9]{2})\2(?P[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')