gpt4 book ai didi

python - TypeError: must be string, not datetime.datetime 使用strptime时

转载 作者:太空狗 更新时间:2023-10-29 19:37:20 24 4
gpt4 key购买 nike

我正在尝试在 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com