【问题标题】:TypeError: must be string, not datetime.datetime when using strptimeTypeError:必须是字符串,而不是使用 strptime 时的 datetime.datetime
【发布时间】:2016-09-02 18:30:23
【问题描述】:

我正在尝试在 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 object,但是我该如何让它工作呢?

【问题讨论】:

  • 去掉except: pass,你就会发现问题所在。这就是为什么except:pass 从来都不是一个好主意的原因,当你想传递一个异常时,你应该指定哪个异常。
  • 谢谢,我得到 AttributeError: 'module' object has no attribute 'strptime'

标签: python datetime typeerror strptime


【解决方案1】:

对于将来遇到此问题的任何人,我想我不妨解释一下我是如何做到这一点的。

这是我的代码:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-13
    • 2015-12-03
    • 2015-06-11
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 2018-09-04
    • 2019-07-07
    相关资源
    最近更新 更多