003_007 Python日付のあいまいなクエリは、標準に合わない日付情報を読み込む

1907 ワード

コードは次のとおりです.
#encoding=utf-8

print '  '

#                      

import datetime
import dateutil.parser

def tryParse(date):
    kwargs = {}
    if isinstance(date,(tuple,list)):
        date=' '.join([str(x) for x in date])
    elif isinstance(date, int):
        date=str(date)
    elif isinstance(date,dict):
        kwargs=date
        date = kwargs.pop('date')    
    try:
        try:
            parsedate = dateutil.parser.parse(date, **kwargs)
            print 'date and parse result: %r->%s'%(date,parsedate)
        except ValueError:
            parsedate = dateutil.parser.parse(date,fuzzy=True, **kwargs)
            print 'Fuzzy: %r->%s'%(date,parsedate)
    except Exception,err:
        print "Can't parse"

datelist=["January 3,2003",
         (5,"Oct",55),
         "Thursday, November 18",
         "7/24/04",
         "24-7-2005",
         {'date':"5-10-1998","dayfirst":True},
         "5-10-18",
         19960708,
         "11AM on the 11th day of 11th mothn,in the year of our Lord 1945"]

for date in datelist:
    tryParse(date)

印刷結果は次のとおりです.
中国date and parse result:'January 32003'->2003-01-03 00:00:00 date and parse result:'5 Oct 55'->2055-10-05 00:00:00 date and parse result:'Thursday, November 18'->2014-11-18 00:00:00 date and parse result: '7/24/04'->2004-07-24 00:00:00 date and parse result: '24-7-2005'->2005-07-24 00:00:00 date and parse result: '5-10-1998'->1998-10-05 00:00:00 date and parse result: '5-10-18'->2018-05-10 00:00:00 date and parse result: '19960708'->1996-07-08 00:00:00 Fuzzy: '11AM on the 11th day of 11th mothn,in the year of our Lord 1945'->1945-11-11 11:00:00