如何通过 Python 更新 MySQL 中的时间戳字段? [英] How can I update a timestamp field in MySQL through Python?
本文介绍了如何通过 Python 更新 MySQL 中的时间戳字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下架构的数据库表,
I have database table with the following schema,
hash VARCHAR(32) NOT NULL, region_unit VARCHAR(64) NOT NULL, url VARCHAR(2048) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00', updated_at TIMESTAMPNOT NULL DEFAULT NOW() ON UPDATE NOW(), PRIMARY KEY (hash)
我通过 Python 用以下语句更新:
that I update with the following statement through Python:
INSERT INTO urls (hash, regional_unit, url, created_at, updated_at)
VALUES (%s, %s, %s, %s, %s)
ON DUPLICATE KEY UPDATE hash=hash;
[['...', '...', '...', None, datetime.datetime(2015, 2, 20, 21, 18, 55, 910026)],
['...', '...', '...', None, datetime.datetime(2015, 2, 20, 21, 18, 55, 910046)]]
我的问题是,根据上述陈述,字段 'created_at'
不会更新,即它始终与 'created_at'
字段具有相同的值.
My problem is that, based on the statements above, field 'created_at'
does not get updated, i.e. it always has the same value as 'created_at'
field.
INSERT INTO urls (hash, regional_unit, url, created_at, updated_at) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE hash=hash; [['...', '...', '...', datetime.datetime(2015, 2, 20, 22, 12, 57, 268424), datetime.datetime(2015, 2, 20, 22, 12, 57, 268437)], ['...', '...', '...', datetime.datetime(2015, 2, 20, 22, 12, 57, 268444), datetime.datetime(2015, 2, 20, 22, 12, 57, 268446)]]
self.db_connect()
self.get_curs().executemany("""INSERT INTO urls (hash, regional_unit, url, created_at, updated_at) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE hash=hash;""", [['...', '...', '...', datetime.datetime(2015, 2, 20, 22, 12, 57, 268424), datetime.datetime(2015, 2, 20, 22, 12, 57, 268437)], ['...', '...', '...', datetime.datetime(2015, 2, 20, 22, 12, 57, 268444), datetime.datetime(2015, 2, 20, 22, 12, 57, 268446)]])
self.get_conn().commit()
self.db_disconnect()
推荐答案
试试这个:
a = datetime.datetime(2015, 2, 20, 22, 12, 57, 268437).strftime('%Y-%m-%d %H:%M:%S')
self.get_curs().executemany("""INSERT INTO urls (hash, regional_unit, url, created_at, updated_at) VALUES (%s, %s, %s, %s, %s) ON DUPLICATE KEY UPDATE hash=hash;""", [['...', '...', '...', a, a], ['...', '...', '...', a,a]])
这篇关于如何通过 Python 更新 MySQL 中的时间戳字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文