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



我使用以下代码以特定格式使用日期并遇到以下错误。如何将日期设置为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'

你应该使用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.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'

您应该将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")

最新更新