【发布时间】:2016-09-02 18:30:23
【问题描述】:
我正在尝试在 Python 2.7 中编写一个函数,将一系列数字转换为有效日期。到目前为止,这一切都与转换无关。
以下是相关代码:
import datetime
def convert_date(x,y,z):
orig_date = datetime.datetime(x,y,z)
d = datetime.datetime.strptime(str(orig_date), '%Y-%m-%d %H:%M:%S')
result = d.strftime('%m-%d-%Y')
return orig_date
a = convert_date(13,11,12)
print a
每当我运行它时,我都会得到:
> Traceback (most recent call last):
> File "test.py", line 9, in <module>
> a = convert_date(13,11,12)
> File "test.py", line 5, in convert_date
> d = datetime.datetime.strptime(orig_date, '%Y-%m-%d %H:%M:%S')
> TypeError: must be string, not datetime.datetime
我知道这是因为 strptime 给了我一个 datetime object,但是我该如何让它工作呢?
【问题讨论】:
-
去掉
except: pass,你就会发现问题所在。这就是为什么except:pass从来都不是一个好主意的原因,当你想传递一个异常时,你应该指定哪个异常。 -
谢谢,我得到 AttributeError:
'module' object has no attribute 'strptime'
标签: python datetime typeerror strptime