How can I parse multiple (unknown) date formats in python?

前端 未结 4 1591
死守一世寂寞
死守一世寂寞 2020-12-10 12:50

I have a bunch of excel documents I am extracting dates from. I am trying to convert these to a standard format so I can put them in a database. Is there a function I can th

4条回答
  •  甜味超标
    2020-12-10 13:38

    If you don't want to install a third-party module like dateutil:

    import re
    from datetime import datetime
    dates = ['10/02/09', '07/22/09', '09-08-2008', '9/9/2008', '11/4/2010', ' 03-07-2009', '09/01/2010']
    reobj = re.compile(
        r"""\s*  # optional whitespace
        (\d+)    # Month
        [-/]     # separator
        (\d+)    # Day
        [-/]     # separator
        (?:20)?  # century (optional)
        (\d+)    # years (YY)
        \s*      # optional whitespace""", 
        re.VERBOSE)
    ndates = [reobj.sub(r"\1/\2/20\3", date) for date in dates]
    fdates = [datetime.strftime(datetime.strptime(date,"%m/%d/%Y"), "%m/%d/%Y")
              for date in ndates]
    

    Result:

    ['10/02/2009', '07/22/2009', '09/08/2008', '09/09/2008', '11/04/2010', '03/07/2009', '09/01/2010']
    

提交回复
热议问题