Python 类型错误:使用 strptime 时必须是字符串,而不是 datetime.datetime
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37093454/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
TypeError: must be string, not datetime.datetime when using strptime
提问by Fake Name
I am trying to write a function in Python 2.7 that converts a series of numbers into a valid date. So far, it all works apart form the conversion.
我正在尝试在 Python 2.7 中编写一个函数,将一系列数字转换为有效日期。到目前为止,除了转换之外,这一切都有效。
Here is the relevant code:
这是相关的代码:
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
Whenever I run this, I get:
每当我运行它时,我都会得到:
> 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
I know that this is because strptime
gives me a datetime object
, but how do I get this to work?
我知道这是因为strptime
给了我一个datetime object
,但是我如何让它起作用?
回答by Fake Name
For anyone who runs into this problem in the future I figured I might as well explain how I got this working.
对于将来遇到这个问题的任何人,我想我不妨解释一下我是如何工作的。
Here is my code:
这是我的代码:
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
As I should have figured out from the error message before I posted, I just needed to convert orig_date
to a string
before using strftime
.
正如我应该从错误信息想通了,我之前发布的,我只是需要转换orig_date
到string
使用之前strftime
。
回答by Abhinav Upadhyay
You are getting an exception. In the except
block you are simply doing a pass
. Instead if you do a print
or log the exception you would know what's wrong.
你得到一个例外。在except
块中,您只是在执行pass
. 相反,如果您执行print
或记录异常,您就会知道出了什么问题。
Since you get an exception, the result
object is not created and therefore you get the error.
由于您遇到异常,result
因此不会创建对象,因此您会收到错误消息。