AttributeError:"str"对象没有属性"strftime" [英] AttributeError: 'str' object has no attribute 'strftime'

查看:260
本文介绍了AttributeError:"str"对象没有属性"strftime"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用以下代码以特定格式使用日期,并遇到以下错误..如何将日期设置为m/d/y格式?

I am using the following code to use the date in a specific format and running into following error..how to put date in m/d/y format?

from datetime import datetime, date

def main ():
    cr_date = '2013-10-31 18:23:29.000227'
    crrdate = cr_date.strftime(cr_date,"%m/%d/%Y")

if __name__ == '__main__':
    main()

错误:-

AttributeError: 'str' object has no attribute 'strftime'

推荐答案

您应该使用 datetime 对象,而不是 str .

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

要从字符串获取datetime对象,请使用 datetime.datetime.strptime :

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

这篇关于AttributeError:"str"对象没有属性"strftime"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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