【发布时间】:2020-11-28 00:52:07
【问题描述】:
我想从索引中删除微秒。
我的索引是这样的:
DatetimeIndex(['2003-11-20 13:07:40.895000+00:00',
'2003-11-20 13:16:13.039000+00:00',
'2003-11-20 13:24:44.868000+00:00',
'2003-11-20 13:33:17.013000+00:00',
'2003-11-20 13:41:49.158000+00:00',
'2003-11-20 13:50:20.987000+00:00',
'2003-11-20 13:58:53.132000+00:00',
'2003-11-20 14:07:24.961000+00:00',
'2003-11-20 14:15:57.106000+00:00',
'2003-11-20 14:24:28.935000+00:00',
...
'2003-12-04 19:28:56.025000+00:00',
'2003-12-04 19:37:27.854000+00:00',
'2003-12-04 19:45:59.999000+00:00',
'2003-12-04 19:54:32.143000+00:00',
'2003-12-04 20:03:03.972000+00:00',
'2003-12-04 20:11:36.117000+00:00',
'2003-12-04 20:20:07.946000+00:00',
'2003-12-04 20:28:40.091000+00:00',
'2003-12-04 20:37:11.920000+00:00',
'2003-12-04 20:45:44.065000+00:00'],
dtype='datetime64[ns, UTC]'
我想删除微秒,以便只有这样的东西:'2003-12-04 20:45:44'
我不想将其转换为字符串,因为它需要保留日期时间,因为它是数据帧的索引。
我一直在寻找这个,但我只找到了这个,它不起作用:
df.index.replace(microsecond=0, inplace = True)
你能帮帮我吗?
【问题讨论】:
-
试试
df.index.floor('S') -
我得到这个结果:'2003-11-20 13:07:40+00:00'
-
那个 +00:00 是时区信息,你不需要那个然后试试:
didx.floor('S').tz_localize(None) -
试试
df.index.astype('datetime64[s]') -
also
idx.floor('S')'.tz_convert(None)... 所以不同之处在于当您想更改时区时,tz_convert会将时间更改为新 tz 中的时间,tz_localize保持时间不变并标记新的 tz
标签: python pandas datetime indexing type-conversion