从时间戳中删除特定字符

remove specific characters from time stamp

我有一个相当奇怪的时间格式和数据帧 df 与列 TIMESTAMP:

2016-10-25T09:34:52.051713+01:00
2016-10-25T09:46:14.051620+01:00
2016-10-25T09:51:16.052435+01:00
....

但我需要将数据用作时间信息。首先,我想去掉最后 13 个字符,使其看起来像

2016-10-25T09:34:52
2016-10-25T09:46:14
2016-10-25T09:51:16
....

为此,我尝试了

df['TIMESTAMP'] = df.apply(lambda x: x['TIMESTAMP'][:-13], axis = 1)

来自

但我收到错误消息:

TypeError: string indices must be integers

我不明白。我刚入职 python,但我没发现我做错了什么?

请将转换语句替换为以下代码

df['TIMESTAMP'] = df['TIMESTAMP'].apply(lambda x: x[-4:])

这会将转换函数应用于名为 time stamp 的整个列,并使用相同的列名将其保存回来

你的问题的严格答案是使用 str 访问器,它可以像普通字符串一样获取一个切片,并将该切片应用于 Series 中的每个值:

data = ['2016-10-25T09:34:52.051713+01:00',
        '2016-10-25T09:46:14.051620+01:00',
        '2016-10-25T09:51:16.052435+01:00']

s = pd.Series(data)

print(s.str[:-13])

输出:

0    2016-10-25T09:34:52
1    2016-10-25T09:46:14
2    2016-10-25T09:51:16

但是,我认为你想要的实际上是pd.to_datetime,它会(在合理的范围内)推断你的数据格式并将其转换为datetime 对象:

print(pd.to_datetime(s))

输出:

0   2016-10-25 09:34:52.051713+01:00
1   2016-10-25 09:46:14.051620+01:00
2   2016-10-25 09:51:16.052435+01:00
dtype: datetime64[ns, pytz.FixedOffset(60)]

一个简单的方法是使用列表理解:

df = pd.DataFrame({'TIMESTAMP' : ["2016-10-25T09:34:52.051713+01:00", "2016-10-25T09:46:14.051620+01:00"]})

 TIMESTAMP
0  2016-10-25T09:34:52.051713+01:00
1  2016-10-25T09:46:14.051620+01:00

df['TIMESTAMP'] = [x[:-13] for x in df['TIMESTAMP']]

输出:

TIMESTAMP
0  2016-10-25T09:34:52
1  2016-10-25T09:46:14
df = pd.DataFrame(
    data={
        'TIMESTAMP': [
            '2016-10-25T09:34:52.051713+01:00',
            '2016-10-25T09:46:14.051620+01:00',
            '2016-10-25T09:51:16.052435+01:00'
        ]
    }
)
df['TIMESTAMP'] = df['TIMESTAMP'].apply(lambda x: x[:19])

顺便说一句,你确定不需要保留时区信息吗?

我建议始终使用 datetime package if you deal with any kind of dates. As of Python3.7, functions fromisoformat can digest your ISO format directly, while strftime can convert to any thinkable time format. (For Python3.6 or lower see this 答案)。

在你的情况下,时间戳写在 df['TIMESTAMP']:

from datetime import datetime as dt
df['TIMESTAMP'].apply(lambda x: dt.strftime(dt.fromisoformat(x), '%Y-%m-%dT%H:%M:%S'))

会成功并给出你想要的输出:

             TIMESTAMP
0  2016-10-25T09:34:52
1  2016-10-25T09:46:14
2  2016-10-25T09:51:16