Python Forum
create a function format_date ?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
create a function format_date ?
#1
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 !!!
Reply
#2
datetime.strptime() converts a string to a datetime object.

https://docs.python.org/3/library/dateti...e-behavior
Reply
#3
Do you have a example of the code
Reply
#4
The link describes how to use the function, documents the syntax used to write the data format string, and has multiple examples.
Reply
#5
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)
buran write Apr-24-2023, 06:54 AM:
Please, use proper tags when post code, traceback, output, etc. This time I have added tags for you.
See BBcode help for more info.
Reply
#6
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.
rob101 likes this post
Reply
#7
In addition, you don't even need to have the variable reassignment; you can simply use return datetime.strptime(datum, '%d-%m-%Y')
Sig:
>>> import this

The UNIX philosophy: "Do one thing, and do it well."

"The danger of computers becoming like humans is not as great as the danger of humans becoming like computers." :~ Konrad Zuse

"Everything should be made as simple as possible, but not simpler." :~ Albert Einstein
Reply
#8
FYI: see also: https://pymotw.com/3/datetime/index.html
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a menu and execute a function based on user selection in python? Thedarkphoenix 1 1,310 Nov-23-2022, 07:53 PM
Last Post: Larz60+
  create a function that can count polk203 1 1,650 Apr-12-2020, 12:13 PM
Last Post: ibreeden
  create function let_to_num() Truman 1 6,000 Feb-15-2018, 04:04 AM
Last Post: ka06059

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020