How to convert a string containing date to mysql timestamp format?
P粉925239921
P粉925239921 2024-03-21 21:09:02
0
1
373

I am working in python environment. I have a date string like this - 26 Apr 2022 17:23:17 GMT I want to insert this date into mysql where date column data type is timestamp. How can I achieve this goal?

My variables are like this (id=1, name="Jack", date="26 Apr 2022 17:23:17 GMT")
mycurser = mydb.cursor()
sql = "INSERT INTO sample_table (id,name,date) VALUES (%s, %s, %s)"
val = (id, name, date)
mycurser.execute(sql,val)

Here the date is a string and the mysql data type is a timestamp.

P粉925239921
P粉925239921

reply all(1)
P粉464208937

You can use STR_TO_DATE:

SELECT STR_TO_DATE('26 Apr 2022 17:23:17 GMT', '%d %b %Y %H:%i:%s');
-- 2022-04-26 17:23:17

Use Python script:

sql = """INSERT INTO sample_table (id, name, date)
         SELECT %s, %s, STR_TO_DATE(%s, '%d %b %Y %H:%i:%s')"""
val = (id, name, date)
mycurser.execute(sql, val)
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!