python - 如何将日期时间插入Mysql?
问题描述
我想插入日期时间。我在 python 中看到了很多关于 datetime 的网站。我都试过了。但在我身上不起作用
import numpy as np
import math
import sys
import mysql.connector
from mysql.connector import Error
from datetime import datetime
id_pel = 'PEL0005,PEL0006,PEL0007,PEL0008,PEL0009,PEL0010,PEL0011,PEL0012,PEL0013,PEL0014'
p = [[9,1,7,3,14,3,18,2,22,2],
[2,2,6,4,4,9,3,3,3,7],
[13.9769,12.1656,40.047,28.287,25.1415,47.6875,34.269,38.3822,47.6875,19.575]
]
result = ['C2', 'C2', 'C1', 'C2', 'C2', 'C1', 'C3', 'C1', 'C3', 'C2']
def insertData(id_pel, recency, frequency, monetary, result):
try:
connection = mysql.connector.connect(host='localhost', database='myDB', user='root', password='')
cursor = connection.cursor()
query = """
INSERT INTO clust_result(
id_pel,
recency,
frequency,
monetary,
hasil,
tanggal_cluster
) VALUES (
%s,
%s,
%s,
%s,
%s,
current_date
)
"""
current_date = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
records = zip(id_pel.split(','), p[0],p[1],p[2], result)
cursor.executemany(query,records)
connection.commit()
print("Inserted successfully")
except mysql.connector.Error as error:
print("Failed to insert into MySQL table {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
insertData(id_pel,p[0],p[1],p[2],result)
查询有效。但在数据库中tanggal_cluster
成为2019-11-12 00:00:00
我期待结果:2019-11-12 19:12:30
phpmyadmin 中 tanggal_cluster 的数据类型为 Datetime。
解决方案
[我知道我应该在评论中提出这个问题,但我没有这样做的声誉点。]
您是否有理由不只使用 MySQL 来获取日期时间?通过使用像NOW()这样的函数,您可以获得返回为“YYYY-MM-DD HH-MM-SS”的当前日期/时间。
包含脚本当前返回的内容以及与理想结果有何不同对您很有帮助。
推荐阅读
- visual-studio-2010 - Visual Studio 2010 String.Format 异常
- locust - Locust:如何在两种不同类型的用户之间共享数据
- python - 在推理过程中正确使用 tf.while_loop?
- java - 在 focframwork GUI Table 中,一些单元格显示为空,直到我打开一行进行编辑并返回。由于“maxCharaters”属性
- python-3.x - BeautifulSoup 文件名提示
- pandas - Python pandas根据在另一个数据帧中的查找将列添加到数据帧
- mysql - pandas 查询分组内的分组
- python - Python:如何通过仅按钮播放 mp3 文件以预览声音(使用 Playsound 代替 QSound)
- java - 单击新布局中的按钮时,我的应用程序崩溃
- javascript - React 警告:函数作为 React 子级无效