Created
December 11, 2012 16:38
-
-
Save scraperdragon/4260142 to your computer and use it in GitHub Desktop.
Parse date cleanly, fail if partial
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def parsedate(datestring, silent=False): | |
import dateutil.parser | |
import re | |
if not datestring: return None | |
if re.match('\d{4}-\d{2}-\d{2}', datestring): return datestring | |
info=dateutil.parser.parserinfo(dayfirst=True) | |
value=dateutil.parser.parser(info)._parse(datestring) | |
if value==None: return None | |
retval=[value.year, value.month, value.day] | |
nones = retval.count(None) | |
if nones==3: | |
return None | |
if nones==0: | |
return u"%04d-%02d-%02d"%(retval[0], retval[1], retval[2]) | |
if not silent: | |
raise AttributeError, "Partial date: %s"%datestring | |
return None |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment