AttributeError:'str'对象没有属性'strftime'

时间:2013-11-10 07:37:22

标签: python string datetime

我使用以下代码以特定格式使用日期并运行到以下error..how以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()

错误: -

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

2 个答案:

答案 0 :(得分:21)

您应该使用datetime对象,而不是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

>>> 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'

答案 1 :(得分:0)

您应将cr_date(str)更改为datetime对象,然后将日期更改为特定格式:

environment:
    - LD_LIBRARY_PATH=/home/lib