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

时间:2015-05-13 12:25:04

标签: 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)

这将最终出错:

  

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

我发现了大量信息 - 但似乎我要么直接将其放入sql查询或导入其他内容? 我希望先把时间用在字符串中,然后传递给我的对象。

1 个答案:

答案 0 :(得分:5)

您正在从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函数,并在将项目插入管道中的数据库时调用它。 / p>