convert a date to a string in python

To convert a date to a string in Python, you can use the strftime() method from the datetime module. The strftime() method takes a string as a parameter, which specifies the format of the returned string.

Here is an example code snippet to convert a date object to a string:

main.py
import datetime

today = datetime.date.today()

# Format date as string
date_string = today.strftime('%m/%d/%Y')

print('Today is:', date_string)
146 chars
9 lines

In the above code, we import the datetime module, then obtain today's date using the date.today() method. We then use the strftime() method to format the date as a string, specifying the format %m/%d/%Y, which gives a string in the format 'mm/dd/yyyy'. Finally, we print the date as a string.

You can customize the format string to return the date in different formats as per your requirement.

gistlibby LogSnag