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

后端 未结 4 1970
無奈伤痛
無奈伤痛 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:46

    Consider using dateutil.parser.parse.

    It's a third party library that has a powerful parser which can handle these kinds of things.

    from dateutil.parser import parse
    
    s = 'Thu 2nd May 2013 19:00'
    
    d = parse(s)
    print(d, type(d))
    # 2013-05-02 19:00:00 
    

    A brief caveat (doesn't really occur in your case): if dateutil can't find an aspect of your date in the string (say you leave out the month) then it will default to the default argument. This defaults to the current date with the time 00:00:00. You can obviously over-write this if necessary with a different datetime object.

    The easiest way to install dateutil is probably using pip with the command pip install python-dateutil.

提交回复
热议问题