I'm trying to insert an information in a database. I have created a function in a code (see bellow) to insert a task using the html but I'm not sure the correct syntax to input date format. I have done a try inserting the information directly in the database using the Workbench and to fix the data format issue I have used the "str_to_date" but I do not know how to insert date thru the Code once it will be updated by the html page... is it correct to use the "str_to_date" alternative also in the python code to avoid error during the data input thru HTML?
def insert_action(task):
cursor = get_connection().cursor()
insert = ('INSERT INTO task(id_request, Task, Description, Responsible, email, Issue_Date, Due_Date, Priority, Task_status)VALUES (default, %s, %s, %s, %s,str_to_date(%s, "%m-%d-%Y"), str_to_date(%s, "%m-%d-%Y"), %s, %s)')
data = (task.Action, task.Description, task.Responsible, task.email, task.Issue_Date, task.Due_Date, task.Priority, task.task_status)
cursor.execute(insert, data)
get_connection().commit()
return cursor.lastrowid
CodePudding user response:
converting date to string (and back):
- string to date:
strptime
- date to string:
strftime
Here is example code:
import datetime as dt
# string to date
date_string = '21 jan 2025'
date_value = dt.datetime.strptime(date_string, '%d %b %Y')
print(date_value)
# date to string
date_string = dt.datetime.strftime(date_value, 'dd-mmm-yyyy')
print(date_string)
Here is a useful link: https://www.programiz.com/python-programming/datetime/strptime or use the official python docs.