首页 > 解决方案 > 当索引同时是时间戳和日期时间时,将所有索引值转换为日期时间

问题描述

我想将我的时间序列 DataFrame 的索引转换为日期时间。问题是一些索引是时间戳和一些日期时间。

time                     C1
2020-10-18 13:38:43.349  0.046   
2020-10-18 13:52:34.104  0.099  
1602824859304            1.000   
1602824934121            0.007   

这: df['time'] = pd.to_datetime(df['time'], unit='ms')
产量: ValueError: non convertible value time with the unit 'ms'

这: df["time"] = df["time"].apply(lambda x: pd.to_datetime(x,errors='ignore').strftime('%Y-%m-%d %H:%M') if len(x) !=0 else "----")
产量: AttributeError: 'str' object has no attribute 'strftime'

这是一个类似的问题,但不适用于我的情况:
Convert dataframe column to datetime only if string of length is not zero

我的预期输出是所有索引行都是日期时间格式。

标签: pythonpandasdatetime

解决方案


让我们尝试识别所有时间戳的行并分别转换它们:

mask = df['time'].str.contains(' ')

df['time'] = (pd.to_datetime(df.loc[mask,'time'])
                   .reindex(df.index)
                   .fillna(pd.to_datetime(df.loc[~mask, 'time'], unit='ms'))
                )

输出:

                     time     C1
0 2020-10-18 13:38:43.349  0.046
1 2020-10-18 13:52:34.104  0.099
2 2020-10-16 05:07:39.304  1.000
3 2020-10-16 05:08:54.121  0.007

推荐阅读