首页 > 解决方案 > 如何将日期时间插入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。

标签: pythonmysqlphpmyadmin

解决方案


[我知道我应该在评论中提出这个问题,但我没有这样做的声誉点。]

您是否有理由不只使用 MySQL 来获取日期时间?通过使用像NOW()这样的函数,您可以获得返回为“YYYY-MM-DD HH-MM-SS”的当前日期/时间。

包含脚本当前返回的内容以及与理想结果有何不同对您很有帮助。


推荐阅读