Parse date string and change format

后端 未结 9 667
孤街浪徒
孤街浪徒 2020-11-22 00:58

I have a date string with the format \'Mon Feb 15 2010\'. I want to change the format to \'15/02/2010\'. How can I do this?

9条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 01:58

    Just for the sake of completion: when parsing a date using strptime() and the date contains the name of a day, month, etc, be aware that you have to account for the locale.

    It's mentioned as a footnote in the docs as well.

    As an example:

    import locale
    print(locale.getlocale())
    
    >> ('nl_BE', 'ISO8859-1')
    
    from datetime import datetime
    datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
    
    >> ValueError: time data '6-Mar-2016' does not match format '%d-%b-%Y'
    
    locale.setlocale(locale.LC_ALL, 'en_US')
    datetime.strptime('6-Mar-2016', '%d-%b-%Y').strftime('%Y-%m-%d')
    
    >> '2016-03-06'
    

提交回复
热议问题