如何从python中的日期时间索引中减去半秒? [复制]
Posted
技术标签:
【中文标题】如何从python中的日期时间索引中减去半秒? [复制]【英文标题】:How to subtract a half second from a date time index in python? [duplicate] 【发布时间】:2020-02-06 05:05:11 【问题描述】:如果我有这样的日期时间索引:
DatetimeIndex(['2018-01-22 21:39:00', '2018-01-22 21:39:01',
'2018-01-22 21:39:03', '2018-01-22 21:39:06',
'2018-01-22 21:39:07', '2018-01-22 21:39:08',
'2018-01-22 21:39:09', '2018-01-22 21:39:10',
'2018-01-22 21:39:11', '2018-01-22 21:39:12'], dtype='datetime64[ns]', freq=None)
如何从每个值中减去半秒,以便得到这样的数据时间索引:
DatetimeIndex(['2018-01-22 21:38:59.50', '2018-01-22 21:39:00.50',
'2018-01-22 21:39:02.50', '2018-01-22 21:39:05.50',
'2018-01-22 21:39:06.50', '2018-01-22 21:39:07.50',
'2018-01-22 21:39:08.50', '2018-01-22 21:39:09.50',
'2018-01-22 21:39:10.50', '2018-01-22 21:39:11.50'], dtype='datetime64[ns]', freq=None)
【问题讨论】:
datetime
有一个毫秒字段;减去 500 毫秒。
【参考方案1】:
解决方案
您可以从 DateTimeIndex 对象中减去0.5 seconds
作为datetime.timedelta
对象。
简答
import datetime
dt = datetime.timedelta(seconds=0.5)
pd.DatetimeIndex(datetime_data) - dt
输出:
0 2018-01-22 21:38:59.500
1 2018-01-22 21:39:00.500
2 2018-01-22 21:39:02.500
3 2018-01-22 21:39:05.500
4 2018-01-22 21:39:06.500
5 2018-01-22 21:39:07.500
6 2018-01-22 21:39:08.500
7 2018-01-22 21:39:09.500
8 2018-01-22 21:39:10.500
9 2018-01-22 21:39:11.500
Name: Timestamp, dtype: datetime64[ns]
详细解决方案
1。制作数据
import numpy as np
import pandas as pd
datetime_data = ['2018-01-22 21:39:00', '2018-01-22 21:39:01',
'2018-01-22 21:39:03', '2018-01-22 21:39:06',
'2018-01-22 21:39:07', '2018-01-22 21:39:08',
'2018-01-22 21:39:09', '2018-01-22 21:39:10',
'2018-01-22 21:39:11', '2018-01-22 21:39:12']
dti = pd.DatetimeIndex(datetime_data)
dti
输出:
DatetimeIndex(['2018-01-22 21:39:00', '2018-01-22 21:39:01',
'2018-01-22 21:39:03', '2018-01-22 21:39:06',
'2018-01-22 21:39:07', '2018-01-22 21:39:08',
'2018-01-22 21:39:09', '2018-01-22 21:39:10',
'2018-01-22 21:39:11', '2018-01-22 21:39:12'],
dtype='datetime64[ns]', freq=None)
2。减去
0.5
秒
import datetime
df = pd.DataFrame(dti, columns=['Timestamp'])
dt = datetime.timedelta(seconds=0.5)
df.Timestamp - dt
输出:
0 2018-01-22 21:38:59.500
1 2018-01-22 21:39:00.500
2 2018-01-22 21:39:02.500
3 2018-01-22 21:39:05.500
4 2018-01-22 21:39:06.500
5 2018-01-22 21:39:07.500
6 2018-01-22 21:39:08.500
7 2018-01-22 21:39:09.500
8 2018-01-22 21:39:10.500
9 2018-01-22 21:39:11.500
Name: Timestamp, dtype: datetime64[ns]
【讨论】:
【参考方案2】:您可以使用pd.DateOffset
从每个值中减去 0.5 秒:
df.index - pd.DateOffset(seconds=0.5)
print(df)
DatetimeIndex(['2018-01-22 21:38:59.500000', '2018-01-22 21:39:00.500000',
'2018-01-22 21:39:02.500000', '2018-01-22 21:39:05.500000',
'2018-01-22 21:39:06.500000', '2018-01-22 21:39:07.500000',
'2018-01-22 21:39:08.500000', '2018-01-22 21:39:09.500000',
'2018-01-22 21:39:10.500000', '2018-01-22 21:39:11.500000'],
dtype='datetime64[ns]', name=0, freq=None)
【讨论】:
以上是关于如何从python中的日期时间索引中减去半秒? [复制]的主要内容,如果未能解决你的问题,请参考以下文章