python - 如何插入字符串(Fri Nov 19 16 :23:54 +0800 2010) into a table field whose type is TIMESTAMP?

标签 python mysql

我正在使用Python和MYSQLdb连接到Mysql。 现在我需要在字段中插入字符串“Fri Nov 19 16:23:54 +0800 2010”,我该怎么办?

最佳答案

您可以使用 Python time.strptime() 方法解析该字符串,然后使用 strftime() 将其转换为 MySQL 所需的字符串。不幸的是,我的 Python 2.6 无法处理 %z 指令,但您可以检查该代码的实现:

import datetime

def test_dt(d, f):
    dt = datetime.datetime.strptime(d, f)
    print('%s -> %s' % (d, dt.strftime('%Y-%m-%d %H:%M:%S %Z')))
    print('-' * 10)

test_dt('Fri Nov 19 16:23:54 2010', '%a %b %d %H:%M:%S %Y')
test_dt('Fri Nov 19 16:23:54 +8000 2010', '%a %b %d %H:%M:%S %z %Y')

如果失败并显示 %z,请考虑您是否需要该时区,或者是否可以从字符串中删除它并以其他方式将其应用于 dt 对象。

似乎已报告并解决了 %z 问题:http://bugs.python.org/issue6641

关于python - 如何插入字符串(Fri Nov 19 16 :23:54 +0800 2010) into a table field whose type is TIMESTAMP?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4224710/

相关文章:

Python正在将新变量中的双引号转换为单引号

python - 为 Sendgrid 的电子邮件 API 编码 CSV 文件

python - 合并多个组 ID 以形成一个合并的组 ID?

php - 数据库 : best practice countries, 国家代码,国家电话代码

mysql - 如何在 dolphindb 中创建 View ?

mysql - 如何将时间戳附加到 curdate() 返回的 mysql 时间?

python - 'pyenchant' 问题,CentOS(和 El Capitan)

python - 将 pandas 列转换为特定位置的列表

php - 如何将 varchar 转换为tinyint

mysql - 在mysql中备份整个数据库