How can I update a timestamp field in MySQL through Python?

故事扮演 提交于 2021-01-29 08:01:34

问题


I have database table with the following schema,

schema

hash VARCHAR(32) NOT NULL, regional_unit VARCHAR(64) NOT NULL, url VARCHAR(2048) NOT NULL, created_at TIMESTAMP NOT NULL DEFAULT '0000-00-00 00:00:00', updated_at TIMESTAMP NOT NULL DEFAULT NOW() ON UPDATE NOW(), PRIMARY KEY (hash)

that I update with the following statement through Python:

query

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)]]

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.

EDIT:

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)]]

EDIT2:

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()

回答1:


Try this way:

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]])


来源:https://stackoverflow.com/questions/28636846/how-can-i-update-a-timestamp-field-in-mysql-through-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!