如何在列中为日期或字符串添加字符?

2024-04-19 09:17:20 发布

您现在位置:Python中文网/ 问答频道 /正文

有一个数据帧

它包含列数据框日期,键入对象。示例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'

好吧,如果是datetime,我们转换成字符串:

df.date.dt.strftime('%Y-%m-%d')

出现了这个错误:

AttributeError: Can only use .dt accessor with datetimelike values

为什么会这样?你知道吗


Tags: ofthe数据对象示例dfdatetimedate
1条回答
网友
1楼 · 发布于 2024-04-19 09:17:20

如果要使用^{}第一次将date对象转换为datetimes和^{},则可以将date对象转换为strings for first solution和for next:

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'

对于将字符串添加到dates/datetimes,需要将其转换为字符串。你知道吗

错误2的原因:

AttributeError: Can only use .dt accessor with datetimelike values

Pandas仍然不能很好地支持python date,因此必须转换为datetimes。你知道吗

相关问题 更多 >