Search code examples
pythonpandasdataframedatetimetimedelta

Adding constant time onto datetime column


I have a datetime column where I am trying to add a constant number of seconds to the original time. The end goal is to create a rolling window function with a fixed window based on seconds. The first step is identical to this question.

My question is why is my application of this solution to this question not working? How can I add a constant timedelta to the previous time in order to try and get the 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]

Solution

  • Use to_datetime for datetimes, then remove microseconds by Series.dt.floor and add 3 seconds:

    # 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