Python dateutil.parser.parse parses month first, not day

后端 未结 2 1292
南旧
南旧 2020-12-09 02:04

I\'m using dateutil.parser.parse to format a date from a string. But now it mixes up the month and the day.

I have a string that contains 05.01.20

2条回答
  •  忘掉有多难
    2020-12-09 02:34

    You asked, 'How can I tell the code that the format is dd.mm.yyyy?'

    Since you have already imported dateutil then most direct answer might be to specify the format of the date string but this is quite ugly code:

    >>> dateutil.parser.datetime.datetime.strptime(date_string, '%d.%m.%Y')
    datetime.datetime(2015, 1, 5, 0, 0)
    

    We can see an obvious alternative embedded in the code. You could use that directly.

    >>> from datetime import datetime
    >>> datetime.strptime(date_string, '%d.%m.%Y')
    datetime.datetime(2015, 1, 5, 0, 0)
    

    There are also some newer alternative libraries that offer methods and properties aplenty.

    Simplest to use in this case would be arrow:

    >>> import arrow
    >>> arrow.get(date_string, 'DD.MM.YYYY')
    
    

    Although I find the formatting for arrow easier to remember, pendulum uses Python's old formatting system which might save you having to learn arrow's.

    >>> import pendulum
    >>> pendulum.datetime.strptime(date_string, '%d.%m.%Y')
    
    

提交回复
热议问题