How to get the datetime from a string containing '2nd' for the date in Python?

后端 未结 4 1984
無奈伤痛
無奈伤痛 2020-12-11 09:17

I\'ve got a couple strings from which I want to get the datetime. They are formatted like this:

Thu 2nd May 2013 19:00

I know almost how I

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-11 10:06

    import re
    from datetime import datetime
    def proc_date(x):
        return re.sub(r"\b([0123]?[0-9])(st|th|nd|rd)\b",r"\1",x)
    
    >>> x='Thu 2nd May 2013 19:00'
    >>> proc_date(x)
    'Thu 2 May 2013 19:00'
    >>> datetime.strptime(proc_date(x), '%a %d %B %Y %H:%M')
    datetime.datetime(2013, 5, 2, 19, 0)
    

提交回复
热议问题