coolair
V2EX  ›  问与答

Python 如何处理多个 format 格式?

  •  
  •   coolair · Mar 10, 2017 · 1777 views
    This topic created in 3360 days ago, the information mentioned may be changed or developed.
    value = '2017-01-01'
    datetime.strptime(value, '%Y-%m-%d')

    value 可能是 '20170101', 也可能是 '201701'。
    怎么添加多个 format ,一级一级去匹配。
    2 replies    2017-03-10 15:50:03 +08:00
    xuboying
        1
    xuboying  
       Mar 10, 2017 via Android
    try catch
    coolair
        2
    coolair  
    OP
       Mar 10, 2017
    formats = ['%Y-%m-%d', '%Y%m%d', '%Y%m']
    for item in formats:
    ....try:
    ........datetime.strptime(value, item)
    ....except:
    ........pass
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   2789 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 12:16 · PVG 20:16 · LAX 05:16 · JFK 08:16
    ♥ Do have faith in what you're doing.