Convert string date into date format in python?

后端 未结 3 622
日久生厌
日久生厌 2021-01-21 05:07

How to convert the below string date into date format in python.

input:
date=\'15-MARCH-2015\'

expected output:
2015-03-15

I tried to use

3条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-21 06:08

    The datetime module will help you here. First convert your string to a datetime object using strptime, then convert this object to the required string format with strftime:

    from datetime import datetime
    datetime.strftime(datetime.strptime('15-MARCH-2015','%d-%B-%Y'),'%Y-%m-%d')
    

    Will yield:

    '2015-03-15'
    

    Notice the string format '%d-%B-%Y' conforms to the string as you have it and '%Y-%m-%d' to the format you want it to be in.

提交回复
热议问题