Parsing a date that can be in several formats in python

前端 未结 4 1495
陌清茗
陌清茗 2020-12-02 01:47

I would like to parse a date that can come in several formats, that I know beforehand. If I could not parse, I return nil. In ruby, I do like this:

DATE_FORM         


        
4条回答
  •  长情又很酷
    2020-12-02 02:26

    After your tip, RocketDonkey, and the one from Bakuriu, I could write a shorter version. Any problem with it?

    def parse_or_none(date):
        for date_format in DATE_FORMATS:
            try:
                return datetime.strptime(date, date_format)
            except ValueError:
                pass
        return None
    

提交回复
热议问题