Skip to content Skip to sidebar Skip to footer

Handling The Different Results From Parsedatetime

I'm trying to learn python after spending the last 15 or so years working only in Perl and only occasionally. I can't understand how to handle the two different kinds of results fr

Solution 1:

I know this is an old question but I ran into this yesterday and the answer here is incomplete (it will fail in the case that parse() returns a datetime).

From the parsedatetime docs:

parse() returns a tuple ( result, type ) where type specifies one of:

   0 = not parsed at all
   1 = parsed as a date (of type struct_time)
   2 = parsed as a time (of type struct_time)
   3 = parsed as a datetime (of type datetime.datetime)

Which is a little weird and maybe not the clearest way to do it, but it works and is pretty useful.

Here's a little chunk of code that will convert whatever it returns to a proper python datetime:

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

Solution 2:

Use x = time.struct_time(result[0]) and you'll get a struct_time (so that you can check x.tm_mon and x.tm_mday) no matter whether that result[0] is a struct_time itself, or just a 9-tuple (I've never heard of parsedatetime so I don't know why it's inconsistent in its return type, but with this simple approach you can neutralize that inconsistency).


Post a Comment for "Handling The Different Results From Parsedatetime"