Processing various results from parsedatetime

I am trying to learn python after spending the last 15 years working only on Perl and only occasionally.

I can't figure out how to handle two different results from the parse method from Calendar.parse () from parsedatetime

Given this script:

#!/usr/bin/python

import parsedatetime.parsedatetime as pdt
import parsedatetime.parsedatetime_consts as pdc
import sys
import os

# create an instance of Constants class so we can override some of the defaults

c = pdc.Constants()

# create an instance of the Calendar class and pass in our Constants # object instead of letting it create a default

p = pdt.Calendar(c)

while True:
 reply = raw_input('Enter text:')
 if reply == 'stop': 
  break
 else:
  result = p.parse(reply)
  print result
  print

And this launch sample:

Enter the text: tomorrow
(time.struct_time (tm_year = 2009, tm_mon = 11, tm_mday = 28, tm_hour = 9, tm_min = 0, tm_sec = 0, tm_wday = 5, tm_yday = 332, tm_isdst = -1), 1)

Enter the text: 11/28
((2009, 11, 28, 14, 42, 55, 4, 331, 0), 1)

I cannot figure out how to get the output so that I can use the result like this:

print result[0].tm_mon, result[0].tm_mday

This will not work if the input is "11/28", because the output is just a tuple, not a struct_time.

, , . Calendar.parse() . . .

+3
2

, , , ( , parse() -).

parsedatetime docs:

parse() (, ), type :

   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)

, , , .

, , python:

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
+15

x = time.struct_time(result[0]), struct_time ( x.tm_mon x.tm_mday) , result[0] struct_time 9- ( parsedatetime, , , ).

+2

Source: https://habr.com/ru/post/1724142/


All Articles