how do I create a function format_date() which takes a date string as an argument and returns a datetime object.
Example
Print (format_date(“24-10-1973”)
1973-10-24 00:00:00
Thanks !!!
Do you have a example of the code
The link describes how to use the function, documents the syntax used to write the data format string, and has multiple examples.
from datetime import datetime
def format_date(datum):
datestring = datum
newdatastring = datetime.strptime(datestring, '%d-%m-%Y').date()
return newdatastring
print(format_date('24-10-1973'))
Output:
1973-10-24
Question how get the following output
1973-10-24 00:00:00 (datetime-object)
By appending .date()
you force the result to be a date, so without time. Just remove this part.
Another thing is you have to return a datetime object. But you name it "newdatastring". This is confusing because it should not be a string, but a datetime object. Choose a better name.
In addition, you don't even need to have the variable reassignment; you can simply use return datetime.strptime(datum, '%d-%m-%Y')