有一个数据框df
它包含 df.date 列,类型对象。示例 2019-01-01
我想将这个值“T07:00:00+0000”添加到每个日期,所以我想要的输出是 2019-01-01T07:00:00+0000。
我试过了
df.date + 'T07:00:00+0000', as the type of the column object
但是出现了这个错误
TypeError: unsupported operand type(s) for +: 'datetime.date' and 'str'
好吧,如果是日期时间,让我们转换成字符串:
df.date.dt.strftime('%Y-%m-%d')
出现这个错误:
AttributeError: Can only use .dt accessor with datetimelike values
为什么会这样?
最佳答案
如果要使用 Series.dt.strftime
,您可以将日期对象转换为字符串用于第一个解决方案和下一个解决方案首先使用 to_datetime
将 date
对象转换为 datetime
:
from datetime import date
df = pd.DataFrame({'date':[date(2019,1,1)]})
df['date1'] = df.date.astype(str) + 'T07:00:00+0000'
df['date2'] = pd.to_datetime(df.date).dt.strftime('%Y-%m-%d') + 'T07:00:00+0000'
print (df)
date date1 date2
0 2019-01-01 2019-01-01T07:00:00+0000 2019-01-01T07:00:00+0000
错误1的原因:
TypeError: unsupported operand type(s) for +: 'datetime.date' and 'str'
要将字符串添加到日期/日期时间,必须转换为字符串。
错误2的原因:
AttributeError: Can only use .dt accessor with datetimelike values
Pandas 对 python 日期
的支持仍然很差,因此有必要转换为日期时间。
关于python - 如何将字符添加到 pandas 列中的日期或 str?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57917707/