TypeError:描述符'strftime'需要'datetime.date'对象但收到'Text'

use*_*827 14 python datetime

我有一个变量testeddate,其日期为文本格式,如2015年4月25日.我正在尝试将其转换%Y-%m-%d %H:%M:%S为如下:

dt_str = datetime.strftime(testeddate,'%Y-%m-%d %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)

但我遇到了这个错误:

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Text'
Run Code Online (Sandbox Code Playgroud)

我该如何解决这个问题?

And*_*ndy 21

你有一个Text对象.该strftime函数需要一个datetime对象.下面的代码采用了将您转换Textdatetime使用的中间步骤strptime

import datetime
testeddate = '4/25/2015'
dt_obj = datetime.datetime.strptime(testeddate,'%m/%d/%Y')
Run Code Online (Sandbox Code Playgroud)

此时,它dt_obj是一个日期时间对象.这意味着我们可以轻松地将其转换为任何格式的字符串.在您的特定情况下:

dt_str = datetime.datetime.strftime(dt_obj,'%Y-%m-%d %H:%M:%S')
Run Code Online (Sandbox Code Playgroud)

dt_str现在是:

'2015-04-25 00:00:00'
Run Code Online (Sandbox Code Playgroud)

  • 或者可以只使用:dt_str = datetime.strptime(testsdate,'%m /%d /%Y').strftime('%Y-%m-%d%H:%M:%S'),假设import是:从datetime导入datetime (3认同)
  • 你的进口声明是什么?如果你只是去`import datetime`它会像我一样工作.如果您正在执行`from datetime import datetime`,请将该行更改为`dt_obj = datetime.strptime(testsdate,'%m /%d /%Y')` (2认同)