Python:生成我可以在 MySQL 中使用的日期时间字符串

Python: Generate a date time string that I can use in for MySQL

如何操作:

from time import time
import datetime
current_time = time.strftime(r"%d.%m.%Y %H:%M:%S", time.localtime())
l.add_value('time', current_time)

这将以错误告终:

print time.strftime(r"%d.%m.%Y %H:%M:%S", time.localtime()) exceptions.AttributeError: 'builtin_function_or_method' object has no attribute 'strftime'

我找到了很多信息 - 但似乎我需要将其直接放入 sql 查询或导入其他任何内容? 我想有时间在字符串中先传递给我的对象。

您正在从 time 模块中导入一个 time() 函数。相反,您需要导入模块。替换:

from time import time

与:

import time

演示:

>>> from time import time
>>> current_time = time.strftime(r"%d.%m.%Y %H:%M:%S", time.localtime())
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'builtin_function_or_method' object has no attribute 'strftime'

>>> import time
>>> current_time = time.strftime(r"%d.%m.%Y %H:%M:%S", time.localtime())
>>> current_time
'13.05.2015 15:26:45'

作为旁注,另一种将时间戳附加到数据库中已抓取项目的选项是使用 NOW() MySQL 函数并在将项目插入到管道中的数据库。