Python:生成一个可用于MySQL的日期时间字符串

Chr*_*ris 2 python mysql time scrapy

这该怎么做:

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)
Run Code Online (Sandbox Code Playgroud)

这将最终出错:

print time.strftime(r"%d.%m.%Y%H:%M:%S",time.localtime())exceptions.AttributeError:'builtin_function_or_method'对象没有属性'strftime'

我发现了大量的信息 - 但似乎我要么直接将它放入sql查询或导入其他任何东西?我想首先将字符串中的时间传递给我的对象.

ale*_*cxe 5

您正在time()从time模块导入功能.相反,您需要导入模块.更换:

from time import time
Run Code Online (Sandbox Code Playgroud)

有:

import time
Run Code Online (Sandbox Code Playgroud)

演示:

>>> 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'
Run Code Online (Sandbox Code Playgroud)

作为旁注,另一个在数据库中附加到时间戳的附加选项将是使用NOW()MySQL函数并在将项插入管道中的数据库时调用它.