我正在尝试在 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 对象
,但我该如何让它工作呢?
最佳答案
对于将来遇到此问题的任何人,我想我不妨解释一下我是如何让这个问题起作用的。
这是我的代码:
from datetime import datetime
def convert_date(x,y,z):
orig_date = datetime(x,y,z)
orig_date = str(orig_date)
d = datetime.strptime(orig_date, '%Y-%m-%d %H:%M:%S')
d = d.strftime('%m/%d/%y')
return d
正如我应该在发布之前从错误消息中弄清楚的那样,我只需要在使用 strftime
之前将 orig_date
转换为 string
.
关于python - TypeError: must be string, not datetime.datetime 使用strptime时,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37093454/