Parsing a date in python without using a default

后端 未结 4 592
我寻月下人不归
我寻月下人不归 2021-01-04 05:51

I\'m using python\'s dateutil.parser tool to parse some dates I\'m getting from a third party feed. It allows specifying a default date, which itself defaults

4条回答
  •  庸人自扰
    2021-01-04 06:27

    simple-date does this for you (it does try multiple formats, internally, but not as many as you might think, because the patterns it uses extend python's date patterns with optional parts, like regexps).

    see https://github.com/andrewcooke/simple-date - but only python 3.2 and up (sorry).

    it's more lenient than what you want by default:

    >>> for date in ('2011-10-12', '2011-10', '2011', '10-12', '2011-10-12T11:45:30', '10-12 11:45', ''):
    ...   print(date)
    ...   try: print(SimpleDate(date).naive.datetime)
    ...   except: print('nope')
    ... 
    2011-10-12
    2011-10-12 00:00:00
    2011-10
    2011-10-01 00:00:00
    2011
    2011-01-01 00:00:00
    10-12
    nope
    2011-10-12T11:45:30
    2011-10-12 11:45:30
    10-12 11:45
    nope
    
    nope
    

    but you could specify your own format. for example:

    >>> from simpledate import SimpleDateParser, invert
    >>> parser = SimpleDateParser(invert('Y-m-d(%T| )?(H:M(:S)?)?'))
    >>> for date in ('2011-10-12', '2011-10', '2011', '10-12', '2011-10-12T11:45:30', '10-12 11:45', ''):
    ...   print(date)
    ...   try: print(SimpleDate(date, date_parser=parser).naive.datetime)
    ...   except: print('nope')
    ... 
    2011-10-12
    2011-10-12 00:00:00
    2011-10
    nope
    2011
    nope
    10-12
    nope
    2011-10-12T11:45:30
    2011-10-12 11:45:30
    10-12 11:45
    nope
    
    nope
    

    ps the invert() just switches the presence of % which otherwise become a real mess when specifying complex date patterns. so here only the literal T character needs a % prefix (in standard python date formatting it would be the only alpha-numeric character without a prefix)

提交回复
热议问题