使用Python将Excel导入MySQL并转换日期戳的步骤如下:
import pandas as pd
import mysql.connector
from mysql.connector import Error
from datetime import datetime
df = pd.read_excel('your_excel_file.xlsx')
df['date_column'] = pd.to_datetime(df['date_column'], format='%Y-%m-%d')
try:
connection = mysql.connector.connect(host='your_host',
database='your_database',
user='your_username',
password='your_password')
if connection.is_connected():
db_Info = connection.get_server_info()
print("Connected to MySQL Server version ", db_Info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except Error as e:
print("Error while connecting to MySQL", e)
请将"your_host"、"your_database"、"your_username"和"your_password"替换为实际的MySQL数据库连接信息。
create_table_query = '''CREATE TABLE your_table_name (
column1 datatype,
column2 datatype,
...
date_column DATE);'''
cursor.execute(create_table_query)
print("Table created successfully!")
请将"your_table_name"替换为实际的表名,并根据需要定义其他列和其对应的数据类型。
for row in df.itertuples():
sql = '''INSERT INTO your_table_name (column1, column2, ..., date_column)
VALUES (%s, %s, ..., %s)'''
values = (row.column1, row.column2, ..., row.date_column.date())
cursor.execute(sql, values)
connection.commit()
print("Data inserted successfully!")
请根据实际的列名和数据类型,以及表名进行相应的替换。
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
以上是使用Python将Excel导入MySQL并转换日期戳的完整步骤。在这个过程中,我们使用了pandas库来读取和处理Excel文件,使用了mysql-connector-python库来连接和操作MySQL数据库。通过将日期戳列转换为datetime对象,然后提取日期部分并插入到MySQL表中,实现了日期戳的转换。
领取专属 10元无门槛券
手把手带您无忧上云