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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 18:50:29  来源:igfitidea点击:

TypeError: must be string, not datetime.datetime when using strptime

pythondatetimetypeerrorstrptime

提问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 strptimegives 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_dateto a stringbefore using strftime.

正如我应该从错误信息想通了,我之前发布的,我只是需要转换orig_datestring使用之前strftime

回答by Abhinav Upadhyay

You are getting an exception. In the exceptblock you are simply doing a pass. Instead if you do a printor log the exception you would know what's wrong.

你得到一个例外。在except块中,您只是在执行pass. 相反,如果您执行print或记录异常,您就会知道出了什么问题。

Since you get an exception, the resultobject is not created and therefore you get the error.

由于您遇到异常,result因此不会创建对象,因此您会收到错误消息。