为什么我得到AttributeError:'str'对象没有属性'strftime'?

时间:2020-06-28 16:32:45

标签: python pandas

我正在尝试将日期转换为字符串并得到以下错误。

    Traceback (most recent call last):
  File "C:/BAB/POC/Slam.py", line 113, in <module>
    sheet0[col] = format_datecol(sheet0, col)
  File "C:/BAB/POC/Slam.py", line 85, in format_datecol
    newSheet[datecolumnname] = newSheet[datecolumnname].apply(lambda x: x.strftime('%d%b%Y'))
  File "C:\2020\python\lib\site-packages\pandas\core\series.py", line 3848, in apply
    mapped = lib.map_infer(values, f, convert=convert_dtype)
  File "pandas\_libs\lib.pyx", line 2327, in pandas._libs.lib.map_infer
  File "C:/BAB/POC/Slam.py", line 85, in <lambda>
    newSheet[datecolumnname] = newSheet[datecolumnname].apply(lambda x: x.strftime('%d%b%Y'))
AttributeError: 'str' object has no attribute 'strftime

'

代码在这里...

for col in keycols0:
    if '_DT'.casefold() or 'DATE'.casefold() in col:
        sheet0[col] = format_datecol(sheet0, col)



def format_datecol(newSheet,datecolumnname):
    newSheet[datecolumnname] = newSheet[datecolumnname].apply(lambda x: x.strftime('%d%b%Y'))
    # newSheet[datecolumnname] = newSheet[datecolumnname].apply(lambda x: datetime.strptime(x,'%d%b%Y'))
    return newSheet[datecolumnname]

如果在条件中出现多个错误或以上错误的情况下添加多个值,则会发生问题。请通过以下代码获取错误

for col in keyColumnNames:
        if '_DT'.casefold() in col:
            tempSheet[col] = format_datecol(tempSheet, col)

def format_datecol(newSheet,datecolumnname):
    newSheet[datecolumnname] = newSheet[datecolumnname].apply(lambda x: x.strftime('%d%m%Y'))
    return newSheet[datecolumnname]

会有什么问题?

2 个答案:

答案 0 :(得分:0)

datecolumnname数据为str数据类型,而不为datetime数据类型

答案 1 :(得分:0)

假设您开头有 <div> <div class="container"> <div class="columns is-multiline"> <div class="column is-4"> <div class="has-background-primary"> <p>1</p> </div> </div> <div class="column is-4"> <div class="has-background-primary"> <div class="columns is-multiline"> <div class="column is-12"> <h1>2</h1> </div> <div class="column is-6"> <h1>2.1</h1> </div> <div class="column is-6"> <h1>2.2</h1> </div> </div> </div> </div> <div class="column is-4"> <div class="has-background-primary"> <p>3</p> </div> </div> <div class="column is-4"> <div class="has-background-primary"> <p>4</p> </div> </div> <div class="column is-4"> <div class="has-background-primary"> <div class="columns is-multiline"> <div class="column is-12"> <h1>5</h1> </div> <div class="column is-6"> <h1>5.1</h1> </div> <div class="column is-6"> <h1>5.2</h1> </div> </div> </div> </div> <div class="column is-4"> <div class="has-background-primary"> <p>6</p> </div> </div> </div> </div> </div> ,并且from datetime import datetime的格式为x,请尝试:

'2020-06-28'