【问题标题】:How to extract only time from pandas DatetimeIndex while maintaining the 'datetime64[ns]' dtype?如何在保持 'datetime64[ns]' dtype 的同时仅从 pandas DatetimeIndex 中提取时间?
【发布时间】:2022-07-21 14:43:53
【问题描述】:

我生成了一个 DatetimeIndex,如下所示:

DatetimeIndex(['1970-01-01 09:30:00.015105074',
               '1970-01-01 09:30:00.059901970',
               '1970-01-01 09:30:00.113246707',
               '1970-01-01 09:30:00.113246707',
               '1970-01-01 09:30:00.113246707',
               '1970-01-01 09:30:00.113246707',
               '1970-01-01 09:30:00.113246707',
               '1970-01-01 09:30:00.154178213',
               '1970-01-01 09:30:00.173594287',
               '1970-01-01 09:30:00.202322801',
               ...
               '1970-01-01 15:59:59.544086847',
               '1970-01-01 15:59:59.544121155',
               '1970-01-01 15:59:59.544124809',
               '1970-01-01 15:59:59.544125669',
               '1970-01-01 15:59:59.544126313',
               '1970-01-01 15:59:59.544129843',
               '1970-01-01 15:59:59.544131783',
               '1970-01-01 15:59:59.544132627',
               '1970-01-01 15:59:59.544133264',
               '1970-01-01 15:59:59.871751084'],
              dtype='datetime64[ns]', name=0, length=112673, freq=None)

这是使用代码生成的:

GOOG_msg_df = pd.read_csv('GOOG_msg_5.csv', header = None, index_col = 0)
pd.to_datetime(GOOG_msg_df.index, unit = 's')

我希望只提取时间部分(保留日期)。我尝试了以下方法:

pd.Series(pd.to_datetime(GOOG_msg_df.index, unit = 's').time)

我得到:

0         09:30:00.015105
1         09:30:00.059901
2         09:30:00.113246
3         09:30:00.113246
4         09:30:00.113246
               ...       
112668    15:59:59.544129
112669    15:59:59.544131
112670    15:59:59.544132
112671    15:59:59.544133
112672    15:59:59.871751
Length: 112673, dtype: object

这种方法的问题是dtypeobject 而不是datetime64[ns]

有没有办法在保持datetime64[ns] dtype 的同时只提取时间分量?这将允许我执行依赖此 dtype 的操作。例如:

pd.to_datetime(GOOG_msg_df.index, unit = 's') > pd.Timestamp('1970-01-01 10:00:00')
>>> array([False, False, False, ...,  True,  True,  True])

【问题讨论】:

    标签: python pandas python-datetime datetimeindex dtype


    【解决方案1】:

    用途:

    pd.Series(pd.to_timedelta(GOOG_msg_df.index, unit = 's').time.astype(str))
    

    【讨论】:

      猜你喜欢
      • 2019-03-17
      • 1970-01-01
      • 2020-04-28
      • 2016-11-26
      • 1970-01-01
      • 2021-02-19
      • 2020-07-13
      • 2022-08-15
      • 2022-01-02
      相关资源
      最近更新 更多