如何将datetime输出datetime.datetime转换为datetime?

时间:2013-10-23 05:53:01

标签: python-2.7

我编写了以下代码,它以datetime.datetime.('current date and time')格式提供当前时间的输出,但我希望输出为datetime('current date and time')

我想删除之前的“Datetime”,尝试使用“拆分”但是它无效,会出现以下错误"datetime.datetime' object has no attribute 'split"

有没有人知道如何在python中做到这一点?

提前感谢。

{

from datetime import datetime
test = datetime.now()
test.split('.')[0]

}

1 个答案:

答案 0 :(得分:3)

因为split仅适用于不是datetime.datetime的字符串。这将清除你的困惑 -

hussain@work-desktop:~$ python
Python 2.7.1+ (r271:86832, Sep 27 2012, 21:16:52) 
[GCC 4.5.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from datetime import datetime
>>> test = datetime.now()
>>> print test
2013-10-23 11:49:28.385757
>>> test.split('.')[0]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'datetime.datetime' object has no attribute 'split'
>>> type(test)
<type 'datetime.datetime'>
>>> test.strftime('%Y-%m-%d %H:%M:%S')
'2013-10-23 11:49:28'