如何快速比较Python中解析的XML的日期?

时间:2014-05-12 20:27:02

标签: python xml python-3.x

我正在使用Python 3中的一个函数来查询eBird API中的小块XML,并用minidom解析它们。该函数定位并比较两个请求的XML块的日期,返回最新的。下面的代码完成了它的工作,但是我想问一下是否有一种更简单的方法(for循环似乎没有必要,因为XML的每一位都只有一个日期,并且逐位比较返回的字符串片段似乎笨重)。有没有更快的方法来产生相同的结果?

from xml.dom import minidom
import requests

def report(owl):
    #GETS THE MOST RECENT OBSERVATION FROM BOTH USA AND CANADA
    usa_xml = requests.get('http://ebird.org/ws1.1/data/obs/region_spp/recent?rtype=country&r=US&sci=surnia%20ulula&back=30&maxResults=1&includeProvisional=true')
    canada_xml = requests.get('http://ebird.org/ws1.1/data/obs/region_spp/recent?rtype=country&r=CA&sci=surnia%20ulula&back=30&maxResults=1&includeProvisional=true')
    usa_parsed = minidom.parseString(usa_xml.text)
    canada_parsed = minidom.parseString(canada_xml.text)

    #COMPARES THE RESULTS AND RETURNS THE MOST RECENT
    usa_raw_date = usa_parsed.getElementsByTagName('obs-dt')
    canada_raw_date = canada_parsed.getElementsByTagName('obs-dt')
    for date in usa_raw_date:
        usa_date = str(date.childNodes[0].nodeValue)   
    for date in canada_raw_date:
        canada_date = str(date.childNodes[0].nodeValue)
    if int(usa_date[0:4]) > int(canada_date[0:4]):
        most_recent = usa_date
    elif int(usa_date[5:7]) > int(canada_date[5:7]):
        most_recent = usa_date
    elif int(usa_date[8:10]) > int(canada_date[8:10]):
        most_recent = usa_date
    elif int(usa_date[11:13]) > int(canada_date[11:13]):
        most_recent = usa_date
    elif int(usa_date[14:16]) > int(canada_date[14:16]):
        most_recent = usa_date
    else:
        most_recent = canada_date
    return most_recent

1 个答案:

答案 0 :(得分:2)

使用datetime.datetime.strftime()将日期解析为datetime.datetime()个对象,然后使用我们max()来返回更大的值(最近的):

usa_date = datetime.datetime.strptime(
    usa_raw_date[-1].childNodes[0].nodeValue, '%Y-%m-%d %H:%M')
canada_date = datetime.datetime.strptime(
    canada_raw_date[-1].childNodes[0].nodeValue, '%Y-%m-%d %H:%M')
return max(usa_date, canada_date)

现在针对您提供的网址运行此操作,结果是:

>>> usa_date = datetime.datetime.strptime(
...     usa_raw_date[-1].childNodes[0].nodeValue, '%Y-%m-%d %H:%M')
>>> canada_date = datetime.datetime.strptime(
...     canada_raw_date[-1].childNodes[0].nodeValue, '%Y-%m-%d %H:%M')
>>> usa_date, canada_date
(datetime.datetime(2014, 5, 5, 11, 0), datetime.datetime(2014, 5, 11, 18, 0))
>>> max(usa_date, canada_date)
datetime.datetime(2014, 5, 11, 18, 0)

返回datetime.datetime()个对象;如果返回一个字符串对你很重要,你总是可以返回:

return max(usa_date, canada_date).strftime('%Y-%m-%d %H:%M')

e.g。将datetime对象再次格式化为字符串。