无年、月、日的时间戳数组算法

2024-10-02 08:14:31 发布

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

我正在处理一个用Pandas阅读的CSV文件。其中一列(不是索引)是时间戳数据,如下所示:

sent>23:56:51.748912

前缀是sent>,后跟小时、分钟、秒、微秒。我想修改所有这些时间戳条目,以便时间向后移动11小时。所以上面的例子是这样的:

^{pr2}$

我期待/希望模运算中有足够聪明的东西,使sent>09:02:13.245511的条目向后移动11时将变成sent>22:02:13.245511。在

我有点困难,因为纽姆和熊猫都想要一年,一个月,一天,但我没有。到目前为止,我看到的文档和示例都相当简洁。我尝试过将数据存储在各种不同的结构中(总结如下),但到目前为止似乎没有任何效果。在

(还在学习纽比/熊猫。。。请对我放轻松…)以下是我尝试过的:

import pandas as pd
import numpy as np
import datetime

df = pd.read_csv(filename, header=None, delimiter=' ', skiprows=2, 
                 skipfooter=2, names=colnames, index_col=False, engine='python')

senttime_col = np.array(df['sent_time'], dtype='str')
senttime_col = np.char.lstrip(senttime_col, 'sent>')
# this creates np array of strings with elements like: 23:56:51.748585

senttimes_ts = pd.to_datetime(df['sent_time'])
# this creates TimeSeries with elements like: sent>23:56:51.748585

senttimes_ts.tshift(pd.Timedelta('-11 hours'))
# ValueError: Freq was not given and was not set in the index

senttimes_df = pd.DataFrame(senttime_col, index=None)
senttimes_df.shift(periods=-11, freq=pd.Timedelta(hours=1))
# TypeError: unsupported operand type(s) for +: 'numpy.int64' and 'Timedelta'

senttimes = np.datetime64(senttime_col)
# ValueError: Could not convert object to NumPy datetime

senttimes = np.datetime64(senttime_col, 'h:m:s.us') 
# TypeError: Invalid datetime unit "h:m:s.us" in metadata
senttimes = np.array(senttime_col, dtype='datetime64[us]')
# ValueError: Error parsing datetime string "00:16:51.748269" at position 2

timelist = [datetime.datetime.strptime(x, '%H:%M:%S.%f') for x in senttime_col]
# ValueError: time data 'None' does not match format '%H:%M:%S.%f'

Tags: importnonedfdatetimeindexnp时间not
1条回答
网友
1楼 · 发布于 2024-10-02 08:14:31

假设,s是一个系列的列:

s = pd.Series(['sent>12:56:51.748912'] * 10000)

# this removes the 'sent>' string from the beginning
s = s.str[5:]

我将使用这个函数来查找我已经解析过的日期-

^{pr2}$

然后,我们将结果保存回s。注意:我没有遇到这个问题-“我遇到了一些困难,因为NumPy datetime64和Pandas TimeSeries都想要完整的年、月和日,但我没有这些内容。”

s = lookup2(s)

In [156]: s.head()
Out[156]: 
0   2015-05-10 12:56:51.748912
1   2015-05-10 12:56:51.748912
2   2015-05-10 12:56:51.748912
3   2015-05-10 12:56:51.748912
4   2015-05-10 12:56:51.748912
dtype: datetime64[ns]

将时间向后移动11小时-

In [154]: t = (s - pd.Timedelta('11 hours')).dt.time

In [155]: t.head()
Out[155]: 
0    23:56:51.748912
1    23:56:51.748912
2    23:56:51.748912
3    23:56:51.748912
4    23:56:51.748912
dtype: object

请告诉我这对你是否有用。在

相关问题 更多 >

    热门问题