无法使用PyMySQL插入日期

时间:2017-06-30 12:12:58

标签: python mysql python-2.7 pymysql

insert语句如下所示:

INSERT INTO events(ts, domain, url, lat_lon, sha1_hash)
VALUES (STR_TO_DATE(%s, '%Y-%m-%dT%H:%i:%sZ'), %s, %s, %s, sha1(url))

当我尝试使用executemany发送批处理时,我收到此错误:

Traceback (most recent call last):
  File "/vagrant/workspace/gdelt/gdelt_all.py", line 41, in <module> read_files()
  File "/vagrant/workspace/gdelt/gdelt_all.py", line 33, in read_files cursor.executemany(INSERT_FOUR, four)
  File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 195, in executemany self.rowcount = sum(self.execute(query, arg) for arg in args)
  File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 195, in <genexpr> self.rowcount = sum(self.execute(query, arg) for arg in args)
  File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 164, in execute query = self.mogrify(query, args)
  File "/usr/local/lib/python2.7/dist-packages/pymysql/cursors.py", line 143, in mogrify query = query % self._escape_args(args, conn)
ValueError: unsupported format character 'Y' (0x59) at index 83

我试图逃避Y以确定这是否是正确的起点,但这并没有帮助。有什么想法吗?

1 个答案:

答案 0 :(得分:4)

用于指定日期格式的转义%;这样它就不会被Cursor.execute*(...)

处理
insert into events(ts, domain, url, lat_lon, sha1_hash) values 
(STR_TO_DATE(%s, '%%Y-%%m-%%dT%%H:%%i:%%sZ'), %s, %s, %s, sha1(url))