我花了大约15年左右的时间在Perl工作并且只是偶尔学习python.
我无法理解如何处理来自parsedatetime的Calendar.parse()的解析方法的两种不同类型的结果
鉴于此脚本:
#!/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
Run Code Online (Sandbox Code Playgroud)
这个示例运行:
输入文字:明天
(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)输入文字:11/28
((2009,11,28,14,42,55,4,331,0 ),1)
我无法弄清楚如何获得输出,以便我可以如此使用结果:
print result[0].tm_mon, result[0].tm_mday
Run Code Online (Sandbox Code Playgroud)
这在输入为"11/28"的情况下不起作用,因为输出只是一个元组而不是struct_time.
可能是一件简单的事......但不适合这个新手.从我的角度来看,Calendar.parse()的输出是不可预测的并且难以使用.任何帮助赞赏.蒂亚.
joe*_*eld 15
我知道这是一个老问题,但我昨天遇到了这个问题,这里的答案是不完整的(在parse()返回日期时间的情况下会失败).
从parsedatetime文档:
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)
Run Code Online (Sandbox Code Playgroud)
这有点奇怪,也许不是最清楚的方法,但它起作用并且非常有用.
这里有一小段代码可以将它返回的内容转换为适当的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
Run Code Online (Sandbox Code Playgroud)