带有pandas时间戳的日期偏移量

2024-10-02 00:23:34 发布

您现在位置:Python中文网/ 问答频道 /正文

我创建了一个DataFrame,其中有一个日期时间和一个列,它表示自从我定义为1月1日1900 00:00以来的分钟数。我只对分钟级的精确度感兴趣。在

    from pandas.tseries.offsets import *

    df = pd.DataFrame([pd.Timestamp('1900-01-01 00:00:00.000000'),
              pd.Timestamp('1900-01-01 00:01:00.000000'),
              pd.Timestamp('1900-01-01 00:02:00.000000'),],
              columns=['datetimeinput'])

用这个函数可以正常工作

^{pr2}$

我可以将timekey列从epoch恢复为0,1,2分钟,其中:

    df.loc[:,'timekey']= MinsSince1900(df['datetimeinput']) 

但是,当我尝试反转此过程并使用以下函数将时间键转换回时间时:

    def CreateTimefromKey(t):
        x=pd.Timestamp('1900-01-01 00:00:00.000000') + DateOffset(minutes=t)
        y = x.to_datetime()
        return y

我收到一条错误消息

    TypeError: unsupported type for timedelta minutes component: Series

很明显,我在这里用偏移量、时间戳和序列做了一些错误的事情。但我想如果它能用一种方法,我可以逆转这个过程。在

如果有人能指出我错在哪里,我将非常感激,谢谢


Tags: 函数fromdataframedf定义过程错误时间
1条回答
网友
1楼 · 发布于 2024-10-02 00:23:34

您可以将一系列timedelta64[ns]添加到epoch(Pandas时间戳):

import pandas as pd
df = pd.DataFrame([pd.Timestamp('1900-01-01 00:00:00.000000'),
          pd.Timestamp('1900-01-01 00:01:00.000000'),
          pd.Timestamp('1900-01-01 00:02:00.000000'),],
          columns=['datetimeinput'])
epoch = pd.Timestamp('1900-01-01 00:00:00.000000')
df['timekey'] = (df['datetimeinput'] - epoch) / pd.Timedelta(minutes=1)
df['date'] = pd.to_timedelta(df['timekey'], unit='m') + epoch

收益率

^{pr2}$

相关问题 更多 >

    热门问题