Python AttributeError: 'str' 对象没有属性 'strftime'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/19887353/
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
AttributeError: 'str' object has no attribute 'strftime'
提问by user2955256
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?
我正在使用以下代码以特定格式使用日期并遇到以下错误..如何将日期放入 m/d/y 格式?
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()
Error:-
错误:-
AttributeError: 'str' object has no attribute 'strftime'
回答by falsetru
You should use datetime
object, not str
.
您应该使用datetime
object,而不是str
.
>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'
To get the datetime object from the string, use datetime.datetime.strptime
:
要从字符串中获取日期时间对象,请使用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'
回答by hichem jedidi
you should change cr_date(str) to datetime object then you 'll change the date to the specific format:
您应该将 cr_date(str) 更改为 datetime 对象,然后将日期更改为特定格式:
cr_date = '2013-10-31 18:23:29.000227'
cr_date = datetime.datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
cr_date = cr_date.strftime("%m/%d/%Y")