MySQL 错误 'Incorrect datetime value' 解决方法 - 时间戳转换

在使用 MySQL 数据库时,可能会遇到以下错误:

error: code = InvalidArgument desc = Incorrect datetime value: '1681609074331' for column 'optime' at row 1 (errno 1292) (sqlstate 22007) (CallerID: xller9w9ptvm9si08uie): Sql: 'insert into nepu(username, 'password', optime) values (:vtg1, :vtg2, :vtg3)', BindVars: {REDACTED}

这个错误通常是由于时间戳格式不正确导致的。MySQL 数据库中的 datetime 类型通常要求时间戳是以秒为单位的整数值。如果你使用的是以毫秒为单位的时间戳,那么需要将其除以 1000 以转换为秒。

解决方法

以下是一个示例代码,用于将时间戳转换为正确的格式并插入数据库:

import datetime
import pymysql

# 连接数据库
conn = pymysql.connect(host='localhost', user='root', password='password', db='mydb')
cursor = conn.cursor()

# 获取当前时间戳,以毫秒为单位
timestamp = 1681609074331

# 将时间戳除以1000,转换为以秒为单位
timestamp = timestamp / 1000

# 将时间戳转换为datetime对象
dt_object = datetime.datetime.fromtimestamp(timestamp)

# 将datetime对象转换为字符串格式
optime = dt_object.strftime('%Y-%m-%d %H:%M:%S')

# 插入数据到数据库
username = 'user1'
password = 'password1'
cursor.execute("INSERT INTO nepu(username, password, optime) VALUES (%s, %s, %s)", (username, password, optime))
conn.commit()

# 关闭连接
cursor.close()
conn.close()

在这个示例代码中,我们将时间戳除以 1000 并转换为 datetime 对象,然后将其转换为字符串格式,并将其插入到数据库中。这样就可以避免由于时间戳格式不正确导致的错误。

总结

MySQL 错误 'Incorrect datetime value' 通常是由于时间戳格式不正确导致的。确保时间戳是以秒为单位的整数值,或者将毫秒级时间戳转换为秒级时间戳,就可以解决这个问题。

MySQL 错误 'Incorrect datetime value' 解决方法 - 时间戳转换

原文地址: https://www.cveoy.top/t/topic/nqYc 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录