Fak*_*ame 10 python datetime strptime typeerror
我试图在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
Run Code Online (Sandbox Code Playgroud)
每当我运行这个,我得到:
回溯(最近一次调用最后一次):文件"test.py",第9行,在= convert_date(13,11,12)文件"test.py",第5行,在convert_date d = datetime.datetime.strptime(orig_date) ,'%Y-%m-%d%H:%M:%S')
TypeError:必须是string,而不是datetime.datetime
我知道这是因为strptime给了我一个datetime object,但我怎么能让它起作用呢?
Fak*_*ame 18
对于将来遇到这个问题的任何人,我想我也可以解释一下我是如何工作的.
这是我的代码:
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
Run Code Online (Sandbox Code Playgroud)
正如我在发布之前应该从错误消息中弄清楚的那样,我只需要在使用之前转换orig_date为a .stringstrftime