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

标签 python datetime typeerror strptime

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

相关文章:

datetime - BadFormat 在使用 Chrono 时将字符串解析为最新

sql - 在 BigQuery 标准 SQL 中将 DATETIME 转换为 STRING,处理 STRUCT 的 ARRAY

python - Python 中的 dict() 问题,TypeError :'tuple' 对象不可调用

javascript - 当我尝试访问新的工作表 ID () 时,Google 应用脚本在不同文件夹中复制脚本时出现类型错误

python - 为什么我无法在 Ubuntu 16.04 上使用 pip 安装 numpy 包?

python - Django基础模板 View 方法

python (2.7) : dynamically adding classmethods

python - 使用 pandas 来自 excel 的列数据框中的最后一个单元格

datetime - 返回一天时间对象的本地开始时间

javascript - 对象[object Object]的属性 '$.fn.toggleHeightAndOpacity'不是函数