Python 类型错误:描述符 'strftime' 需要一个 'datetime.date' 对象,但收到了一个 'Text'

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30112357/
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 07:58:43  来源:igfitidea点击:

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Text'

pythondatetime

提问by user2125827

I have a variable testeddatewhich has a date in text format like 4/25/2015. I am trying convert it to %Y-%m-%d %H:%M:%Sas follows:

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

dt_str = datetime.strftime(testeddate,'%Y-%m-%d %H:%M:%S')

but I am running into this error:

但我遇到了这个错误:

TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Text'

How do I resolve this?

我该如何解决?

采纳答案by Andy

You have a Textobject. The strftimefunction requires a datetime object. The code below takes an intermediate step of converting your Textto a datetimeusing strptime

你有一个Text对象。该strftime函数需要一个日期时间对象。下面的代码需要将您的转换Textdatetimeusing的中间步骤strptime

import datetime
testeddate = '4/25/2015'
dt_obj = datetime.datetime.strptime(testeddate,'%m/%d/%Y')

At this point, the dt_objis a datetime object. This means we can easily convert it to a string with any format. In your particular case:

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

dt_str = datetime.datetime.strftime(dt_obj,'%Y-%m-%d %H:%M:%S')

The dt_strnow is:

dt_str现在是:

'2015-04-25 00:00:00'

回答by thikonom

A less elegant solution would involve manipulating the string directly.

一个不太优雅的解决方案是直接操作字符串。

testeddate = '4/25/2015'
month, day, year = testeddate.split('/')
testeddate = '-'.join([year, month, day]) + ' 00:00:00'