TypeError:descriptor'strftime'需要一个'datetime.date'对象,但是收到'Text' [英] TypeError: descriptor 'strftime' requires a 'datetime.date' object but received a 'Text'

查看:11031
本文介绍了TypeError:descriptor'strftime'需要一个'datetime.date'对象,但是收到'Text'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

但我遇到这个错误:

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

推荐答案

您有一个文本对象。 strftime 功能需要一个datetime对象。以下代码将使用 Text 转换为 datetime docs.python.org/2/library/time.html#time.strptime> strptime

You have a Text object. The strftime function requires a datetime object. The code below takes an intermediate step of converting your Text to a datetime using strptime

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

此时, dt_obj 一个datetime对象。这意味着我们可以轻松地将其转换为任何格式的字符串。在你的具体情况下:

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

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

dt_str 现在是:

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

这篇关于TypeError:descriptor'strftime'需要一个'datetime.date'对象,但是收到'Text'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆