Package xappy :: Module parsedate
[frames] | no frames]

Source Code for Module xappy.parsedate

 1  #!/usr/bin/env python 
 2  # 
 3  # Copyright (C) 2007 Lemur Consulting Ltd 
 4  # 
 5  # This program is free software; you can redistribute it and/or modify 
 6  # it under the terms of the GNU General Public License as published by 
 7  # the Free Software Foundation; either version 2 of the License, or 
 8  # (at your option) any later version. 
 9  # 
10  # This program is distributed in the hope that it will be useful, 
11  # but WITHOUT ANY WARRANTY; without even the implied warranty of 
12  # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the 
13  # GNU General Public License for more details. 
14  #  
15  # You should have received a copy of the GNU General Public License along 
16  # with this program; if not, write to the Free Software Foundation, Inc., 
17  # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 
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   
29 -def date_from_string(value):
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