Python Forum
create a function format_date ? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: Homework (https://python-forum.io/forum-9.html)
+--- Thread: create a function format_date ? (/thread-39851.html)



create a function format_date ? - Kessie1971 - Apr-23-2023

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 !!!


RE: create a function format_date ? - deanhystad - Apr-23-2023

datetime.strptime() converts a string to a datetime object.

https://docs.python.org/3/library/datetime.html#strftime-and-strptime-behavior


RE: create a function format_date ? - Kessie1971 - Apr-23-2023

Do you have a example of the code


RE: create a function format_date ? - deanhystad - Apr-23-2023

The link describes how to use the function, documents the syntax used to write the data format string, and has multiple examples.


RE: create a function format_date ? - Kessie1971 - Apr-24-2023

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)



RE: create a function format_date ? - ibreeden - Apr-24-2023

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.


RE: create a function format_date ? - rob101 - Apr-24-2023

In addition, you don't even need to have the variable reassignment; you can simply use return datetime.strptime(datum, '%d-%m-%Y')


RE: create a function format_date ? - Larz60+ - Apr-24-2023

FYI: see also: https://pymotw.com/3/datetime/index.html