1

自由形式の日付文字列を意味のある日付に解析しようとしています。これまでのところ、私はこの関数を思いついた:

"""Parse raw date string into YYYY-MM-DD"""
def __parseDate(self, rawDate):
    if len(rawDate) == 0:
        return u""
    if "{{Birth year and age|" in rawDate:
        rawDate = rawDate.replace("{{","").replace("}}","")
        year = rawDate.split("|")[1].strip()
        return year + "-01-01"
    elif "{{Birth date and age|" in rawDate:
        rawDate = rawDate.replace("{{","").replace("}}","")
        year = rawDate.split("|")[1].strip()
        month = rawDate.split("|")[2].strip()
        day = rawDate.split("|")[3].strip()
        if len(month) == 1:
            month = "0" + month
        if len(day) == 1:
            day = "0" + day
        return year + "-" + month + "-" + day
    elif "{{" in rawDate:
        self.__log(u"XXX Date parse error (unknown template): " + rawDate)
        return u"1770-01-01"
    elif re.match("([a-zA-Z]* [0-9][0-9]?, [0-9][0-9][0-9][0-9])", rawDate):
        match = re.findall("([a-zA-Z]* [0-9][0-9]?, [0-9][0-9][0-9][0-9])", rawDate)[0]
        parts = match.replace(",","").split(" ")
        year = parts[2].strip()
        month = parts[0].replace(".","").strip()
        day = parts[1].strip()
        tryAgain = False
        try:
            month = str(strptime(month,'%B').tm_mon)
        except:
            tryAgain = True
            pass
        try:
            if tryAgain:
                month = str(strptime(month,'%b').tm_mon)
        except:
            self.__log(u"XXX Date parse error: " + rawDate)
            return u"1770-01-01"
            pass

        if len(month) == 1:
            month = "0" + month
        if len(day) == 1:
            day = "0" + day
        return year + "-" + month + "-" + day
    elif re.match("[0-9][0-9][0-9][0-9]-[0-9][0-9]?-[0-9][0-9]?", rawDate):
        parts = rawDate.split("-")
        year = parts[0].strip()
        month = parts[1].strip()
        day = parts[2].strip()
        if len(month) == 1:
            month = "0" + month
        if len(day) == 1:
            day = "0" + day
        return year + "-" + month + "-" + day
    else:
        self.__log(u"XXX Date parse error: " + rawDate)
        return u"1770-01-01"

私は正しい方向に進んでいますか、それとももっと良い方法がありますか?

自由形式の文字列による更新これは、Wikiページ、特に個人データテンプレートからのものであることを意味します。このテンプレートの日付フィールドは、人間が何かを入力したという点で自由形式です。通常、これは任意の数の形式の日付であるか、それ自体が日付を説明する別のWikiテンプレートです。フィールドにある可能性のあるもののいくつかの例を次に示します。

{{Birth year and age|1933}}
August 23, 1967
1990-01-29
23 August 1967
1999
a;lsdfhals;djkfh
4

1 に答える 1

5

おそらく究極はparsedatetimeです。

別の選択肢はですdateutil

于 2012-10-03T22:41:56.753 に答える