python format 01-01-2019 in python

To format a date in Python, you can make use of the strftime() method from the datetime module. Here's how you can format the date "01-01-2019" as per your requirement:

main.py
from datetime import datetime

date_str = "01-01-2019"
date_obj = datetime.strptime(date_str, "%d-%m-%Y")
formatted_date = date_obj.strftime("%Y-%m-%d")

print(formatted_date)
176 chars
8 lines

In the code above, we first use strptime() to convert the date string into a datetime object, by specifying the current format of the date string ("%d-%m-%Y"). We then use strftime() to format the date object into the desired format ("%Y-%m-%d"). Finally, we print the formatted date which would be "2019-01-01".

Hope this helps!

related categories

gistlibby LogSnag