如何在Pandas中将索引转换为日期时间?

4

i have index like this

Index(['00:00:00', '00:15:00', '00:30:00', '00:45:00', '01:00:00', '01:15:00',
       '01:30:00', '01:45:00', '02:00:00', '02:15:00', '02:30:00', '02:45:00'],
      dtype='object', name='time') 

我需要将其转换为时间格式 %H:%M:%S,该怎么修改?

1个回答

2
我认为你需要:

我认为你需要:

idx = pd.Index(['00:00:00', '00:15:00', '00:30:00', '00:45:00', '01:00:00', '01:15:00',
       '01:30:00', '01:45:00', '02:00:00', '02:15:00', '02:30:00', '02:45:00'],
      dtype='object', name='time') 

DatetimeIndex需要一些日期,默认情况下会添加今天的日期:

print (pd.to_datetime(idx))
DatetimeIndex(['2018-01-25 00:00:00', '2018-01-25 00:15:00',
               '2018-01-25 00:30:00', '2018-01-25 00:45:00',
               '2018-01-25 01:00:00', '2018-01-25 01:15:00',
               '2018-01-25 01:30:00', '2018-01-25 01:45:00',
               '2018-01-25 02:00:00', '2018-01-25 02:15:00',
               '2018-01-25 02:30:00', '2018-01-25 02:45:00'],
              dtype='datetime64[ns]', name='time', freq=None)

或者可以添加自定义日期:
print (pd.to_datetime('2015-01-01 ' + idx))
DatetimeIndex(['2015-01-01 00:00:00', '2015-01-01 00:15:00',
               '2015-01-01 00:30:00', '2015-01-01 00:45:00',
               '2015-01-01 01:00:00', '2015-01-01 01:15:00',
               '2015-01-01 01:30:00', '2015-01-01 01:45:00',
               '2015-01-01 02:00:00', '2015-01-01 02:15:00',
               '2015-01-01 02:30:00', '2015-01-01 02:45:00'],
              dtype='datetime64[ns]', freq=None)

另一种解决方案是创建TimedeltaIndex:
print (pd.to_timedelta(idx))

TimedeltaIndex(['00:00:00', '00:15:00', '00:30:00', '00:45:00', '01:00:00',
                '01:15:00', '01:30:00', '01:45:00', '02:00:00', '02:15:00',
                '02:30:00', '02:45:00'],
               dtype='timedelta64[ns]', name='time', freq=None)

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接