【问题标题】:TypeError: strptime() argument 1 must be str, not float do not understand why this is happeningTypeError: strptime() argument 1 must be str, not float 不明白为什么会这样
【发布时间】:2020-11-10 15:55:57
【问题描述】:

所有,

我得到了如标题所示的上述错误,但我不确定为什么会发生这种情况。我的 row['date'] 值看起来像:2012-10-04T00:00:00。当我调试它的“str”类型时。

row['date'] 的输出是:2016-06-22T00:00:00 2016-06-23T00:00:00 2016-06-23T00:00:00 2016-06-25T00:00:00 2016-06-29T00:00:00 2016-06-30T00:00:00 2016-06-30T00:00:00 2016-07-06T00:00:00 2016-07-07T00:00:00 2016-07-07T00:00:00

for row in data['date_of_incorporation']:
    new_date = datetime.strptime(row, "%Y-%m-%dT%H:%M:%S")

new_date 然后变成一个日期时间对象。

我需要上面的格式,因为我想提取年份和月份:

year = new_date.year
month = new_date.month

但如果它已经在 str 中,我不明白为什么会出现错误:

TypeError: strptime() argument 1 must be str, not float 

【问题讨论】:

  • 对象类型
  • type(row['date']) 的输出是什么?
  • 请澄清:您标记了您的问题pandasdata 也是一个DataFrame?

标签: python pandas date datetime parsing


【解决方案1】:

假设您有一个pandas DataFrame,您可能想要转换为日期时间。之后,您可以使用 dt 访问器获取年份和月份。

import pandas as pd

data = pd.DataFrame({'date_of_incorporation': ['2012-10-04T00:00:00']})

data['date_of_incorporation'] = pd.to_datetime(data['date_of_incorporation'])

data['date_of_incorporation'].dt.year
# 0    2012
# Name: date_of_incorporation, dtype: int64

data['date_of_incorporation'].dt.month
# 0    10
# Name: date_of_incorporation, dtype: int64

...或者生成一定格式的字符串输出:

data['date_of_incorporation'].dt.strftime('%Y-%m')
# 0    2012-10
# Name: date_of_incorporation, dtype: object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-03-28
    • 1970-01-01
    • 1970-01-01
    • 2019-12-02
    • 2019-05-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多