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

后端 未结 4 1979
無奈伤痛
無奈伤痛 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 09:54

    You can preparse the original string to adjust the day to be suitable for your strptime, eg:

    from datetime import datetime
    import re
    
    s = 'Thu 2nd May 2013 19:00'
    amended = re.sub('\d+(st|nd|rd|th)', lambda m: m.group()[:-2].zfill(2), s)
    # Thu 02 May 2013 19:00
    dt = datetime.strptime(amended, '%a %d %B %Y %H:%M')
    # 2013-05-02 19:00:00
    

提交回复
热议问题