gpt4 book ai didi

python - 将常数时间添加到日期时间列

转载 作者:行者123 更新时间:2023-12-05 05:46:52 24 4
gpt4 key购买 nike

我有一个日期时间列,我试图在其中向原始时间添加常数秒数。最终目标是创建一个基于秒的固定窗口的滚动窗口函数。第一步与此相同 question .

我的问题是为什么我对这个问题应用这个解决方案不起作用?我怎样才能添加一个常量 timedelta 到以前的时间以尝试获取 r

# ========== create dataset and try add 3 seconds to datetime column=================================================================== #

import pandas as pd
from datetime import timedelta, datetime


timestamp_list = ["2022-02-07 11:38:08.625",
"2022-02-07 11:38:09.676",
"2022-02-07 11:38:10.084",
"2022-02-07 11:38:10.10000",
"2022-02-07 11:38:11.2320"]

value_list = [1.14338,
1.14341,
1.14340,
1.1434334,
1.1534334]

df = pd.DataFrame.from_dict(zip(timestamp_list, value_list))
df.columns = ['timestamp','value']

# make date time object
df.timestamp = [datetime.strptime(time_i, "%Y-%m-%d %H:%M:%S.%f") for time_i in df.timestamp]

# get the time second value of datetime
df["timestamp_to_sec"] = df["timestamp"].dt.strftime("%Y%m%d %H:%M:%S")

# add 3 seconds to the original timestep
temp = df.timestamp_to_sec + timedelta(seconds=3)
#output with error
0 -83211 days +23:06:15.727111680
1 -83211 days +23:06:16.727111680
2 -83211 days +23:06:17.727111680
3 -83211 days +23:06:17.727111680
4 -83211 days +23:06:18.727111680
Name: timestamp_to_sec, dtype: timedelta64[ns]

最佳答案

使用to_datetime对于日期时间,然后通过 Series.dt.floor 删除微秒并添加 3 秒:

# make date time object
df.timestamp = pd.to_datetime(df.timestamp)

# get the time second value of datetime
df["timestamp"] = df["timestamp"].dt.floor('s') + pd.Timedelta(seconds=3)

print (df)
timestamp value
0 2022-02-07 11:38:11 1.143380
1 2022-02-07 11:38:12 1.143410
2 2022-02-07 11:38:13 1.143400
3 2022-02-07 11:38:13 1.143433
4 2022-02-07 11:38:14 1.153433

关于python - 将常数时间添加到日期时间列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71110578/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com