Created
December 27, 2013 23:22
-
-
Save dtanham/8154025 to your computer and use it in GitHub Desktop.
Sensible date parsing in Python courtesy of http://stackoverflow.com/questions/1810432/handling-the-different-results-from-parsedatetime/5903760#5903760
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
import parsedatetime.parsedatetime as pdt | |
def datetimeFromString( s ): | |
c = pdt.Calendar() | |
result, what = c.parse( s ) | |
dt = None | |
# what was returned (see http://code-bear.com/code/parsedatetime/docs/) | |
# 0 = failed to parse | |
# 1 = date (with current time, as a struct_time) | |
# 2 = time (with current date, as a struct_time) | |
# 3 = datetime | |
if what in (1,2): | |
# result is struct_time | |
dt = datetime.datetime( *result[:6] ) | |
elif what == 3: | |
# result is a datetime | |
dt = result | |
if dt is None: | |
# Failed to parse | |
raise ValueError, ("Don't understand date '"+s+"'") | |
return dt |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment