How to convert Python strings to dates?
In Python, you can use the datetime module to convert a string into a date. Here is an example code:
from datetime import datetime
date_str = "2022-10-15"
date_obj = datetime.strptime(date_str, "%Y-%m-%d")
print(date_obj)
In the code above, we first import the datetime module, then define a string variable date_str containing date information. Next, we use the datetime.strptime function to convert the string into a date object, specifying the format of the date string, such as “%Y-%m-%d” for year-month-day format. Finally, we print the date object.
If you need to convert a date object to a string, you can use the strftime method. Here is an example code:
date_obj = datetime.now()
date_str = date_obj.strftime("%Y-%m-%d")
print(date_str)
In the code above, we first get the current date and time object, then format the date object into a string using the strftime method, and finally print the string.