代码之家  ›  专栏  ›  技术社区  ›  dubbbdan

dateutil和闰年

  •  0
  • dubbbdan  · 技术社区  · 5 年前

    如果我有以下字符串列表:

    a = ['Loc_RaffertytoLong_2004_02_21',
     'Loc_RaffertytoLong_2004_02_22',
     'Loc_RaffertytoLong_2004_02_23',
     'Loc_RaffertytoLong_2004_02_24',
     'Loc_RaffertytoLong_2004_02_26',
     'Loc_RaffertytoLong_2004_02_27',
     'Loc_RaffertytoLong_2004_02_28',
     'Loc_RaffertytoLong_2004_02_29']
    

    我试着用 dateutil :

    from dateutil import parse as dparse
    for i in a:
        print(dparse.parse(i,fuzzy=True))
    

    我得到打印输出:

    2019-02-21 00:00:00
    2019-02-22 00:00:00
    2019-02-23 00:00:00
    2019-02-24 00:00:00
    2019-02-26 00:00:00
    2019-02-27 00:00:00
    2019-02-28 00:00:00
    

    错误是:

    ValueError: ('Unknown string format:', 'Loc_RaffertytoLong_2004_02_29')
    

    我不知道为什么2004年是闰年。

    1 回复  |  直到 5 年前
        1
  •  2
  •   wpercy    5 年前

    如果你看你的输出, dateutil 将您的日期解释为2019年的日期(即 闰年)。

    我通过更改行使您的代码成功:

    print(dparse.parse(i,fuzzy=True))
    

    到:

    print(dparse.parse('-'.join(i.split('_')[2:])))
    

    当我运行整个块时,我得到输出:

    2004-02-21 00:00:00
    2004-02-22 00:00:00
    2004-02-23 00:00:00
    2004-02-24 00:00:00
    2004-02-26 00:00:00
    2004-02-27 00:00:00
    2004-02-28 00:00:00
    2004-02-29 00:00:00
    

    有趣的是,如果我们像这样连接下划线:

    print(dparse.parse('_'.join(i.split('_')[2:])))
    

    它还解释了2019年的日期。这让我觉得问题在于 日期工具 处理下划线。


    您也可以简单地用破折号替换下划线:

    from dateutil import parser
    for i in a:
        print(parser.parse(i.replace('_','-'), fuzzy=True))
    

    打印与上面相同的输出。