How do I convert a string to a date object in python?
The string would be: "24052010"
(corresponding to the format: "%d%m%Y"
)
I don't want a datetime.datetime object, but rather a datetime.date.
To create a date, we can use the datetime() class (constructor) of the datetime module. The datetime() class requires three parameters to create a date: year, month, day.
Python has a built-in method to parse dates, strptime . This example takes the string “2020–01–01 14:00” and parses it to a datetime object. The documentation for strptime provides a great overview of all format-string options.
You can use strptime
in the datetime
package of Python:
>>> import datetime >>> datetime.datetime.strptime('24052010', "%d%m%Y").date() datetime.date(2010, 5, 24)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With