python datetime strptime wildcard

前端 未结 5 2034
有刺的猬
有刺的猬 2021-01-04 02:23

I want to parse dates like these into a datetime object:

  • December 12th, 2008
  • January 1st, 2009

The following will work for the first d

5条回答
  •  一个人的身影
    2021-01-04 02:52

    For anyone who, like me, just want something that "works" without an additional module, this is a quick and dirty solution.

    string_list = ["th", "rd", "nd", "st"]
    time = None
    for str in string_list:
        if (time is not None):
            break
        try:
            match_string = '%B %d' + str +', %Y'
            time = datetime.strptime("December 12th, 2008", match_string)
        except Exception:
            pass
    

提交回复
热议问题