V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
coolair
V2EX  ›  问与答

Python 如何处理多个 format 格式?

  •  
  •   coolair · 2017-03-10 15:40:12 +08:00 · 1367 次点击
    这是一个创建于 2640 天前的主题,其中的信息可能已经有所发展或是发生改变。
    value = '2017-01-01'
    datetime.strptime(value, '%Y-%m-%d')

    value 可能是 '20170101', 也可能是 '201701'。
    怎么添加多个 format ,一级一级去匹配。
    2 条回复    2017-03-10 15:50:03 +08:00
    xuboying
        1
    xuboying  
       2017-03-10 15:43:24 +08:00 via Android
    try catch
    coolair
        2
    coolair  
    OP
       2017-03-10 15:50:03 +08:00
    formats = ['%Y-%m-%d', '%Y%m%d', '%Y%m']
    for item in formats:
    ....try:
    ........datetime.strptime(value, item)
    ....except:
    ........pass
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   947 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 20:19 · PVG 04:19 · LAX 13:19 · JFK 16:19
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.