pythondatetime

Python - Convert String date "17 Apr" to Date "17-04-2018"


I've this string variable: date_string = "17 Apr"

How can I get this: 17-04-2018?

I'm trying with this

datetime_object = datetime.strptime(date_string, "%d %B")

But I'm getting:

builtins.ValueError: time data '17 Apr' does not match format '%d %B

Thanks!


Solution

  • Using datetime module.

    Ex:

    import datetime
    s = "17 Apr"
    print(datetime.datetime.strptime("{0} 2018".format(s), "%d %b %Y").strftime("%d-%m-%Y"))
    

    Output:

    17-04-2018