【发布时间】:2017-02-01 09:29:28
【问题描述】:
我有一个timestamp 列,其中时间戳采用以下格式
2016-06-16T21:35:17.098+01:00
我想从中提取日期和时间。我做了以下事情:
import datetime as dt
df['timestamp'] = df['timestamp'].apply(lambda x : pd.to_datetime(str(x)))
df['dates'] = df['timestamp'].dt.date
这工作了一段时间。但是突然就不行了。
如果我再次执行df['dates'] = df['timestamp'].dt.date,我会收到以下错误
Can only use .dt accessor with datetimelike values
幸运的是,我已将带有 dates 的数据框保存在 csv 中,但我现在想以 23:00:00.051 的格式创建另一列 time
编辑
从原始数据文件(1500 万个样本)来看,timestamp 列如下所示(前 5 个样本):
timestamp
0 2016-06-13T00:00:00.051+01:00
1 2016-06-13T00:00:00.718+01:00
2 2016-06-13T00:00:00.985+01:00
3 2016-06-13T00:00:02.431+01:00
4 2016-06-13T00:00:02.737+01:00
以下命令后
df['timestamp'] = df['timestamp'].apply(lambda x : pd.to_datetime(str(x)))
timestamp 列看起来像 dtype 作为 dtype: datetime64[ns]
0 2016-06-12 23:00:00.051
1 2016-06-12 23:00:00.718
2 2016-06-12 23:00:00.985
3 2016-06-12 23:00:02.431
4 2016-06-12 23:00:02.737
最后
df['dates'] = df['timestamp'].dt.date
0 2016-06-12
1 2016-06-12
2 2016-06-12
3 2016-06-12
4 2016-06-12
编辑 2
发现错误。我已经清理了数据并将数据框保存在 csv 文件中,所以我不必再次进行清理。当我读取 csv 时,时间戳 dtype 变为对象。现在我该如何解决这个问题?
【问题讨论】:
-
这意味着您有一些 duff 值,因此您可以将这些 duff 值强制为
NaT:df['timestamp'] = pd.to_datetime(df['timestamp'], errors='coerce')然后您可以使用dropna删除这些值,然后您可以调用@987654341 @和以前一样 -
df.timestamp.isnull().sum()返回 0 -
抱歉,除非您发布原始数据和错误代码,否则这将成为一种假设性的姿势练习,会浪费时间
-
@chintans OT,而不是
df['timestamp'].apply(lambda x : pd.to_datetime(str(x))),考虑pd.to_datetime(df['timestamp'])。 -
@chintans 要加快转换速度,请指定日期时间字符串的格式 --- 请参阅 this question。
标签: python python-2.7 pandas time-series