'How to add 1 hour before and after to DateTime object with python?
I have records with a set of keys and a datetime column. I would like to write a code that selects each record to generate one-hour before and one-hour after records with one minute frequency. For example, my original dataset looks like the following, such that each key record is unique with its datetime.
| key | datetime |
|---|---|
| 20181027698 | 1/17/2018 12:47:00 PM |
| 20181021819 | 1/1/2018 2:20:00 PM |
| 20181022432 | 3/1/2018 11:10 AM |
The output I desire is in the form of a given key, say, 20181027698, which will have all the values from 1/17/2018 11:47:00 AM up to 1/17/2018 12:47:00 PM. This output will be for before. For after, the output will be all values from 1/17/2018 12:47:00 PM to 1/17/2018 01:47:00 PM for one-minute intervals for each unique key with its given datetime values.
I have seen many codes with SQL examples but can't find anything with Python. Any guidance will be much appreciated. The code I have tried but is not working is
fdf=pd.DataFrame([])
cks=[]
nos=[]
for i in range(0,len(df)):
time=df.iloc[i,2]
x=time-pd.Timedelta(hours=1)
y=time+pd.Timedelta(hours=1)
ck=df.iloc[i,1]
ids=df.iloc[i,0]
l = (pd.DataFrame(columns=['NULL'],
index=pd.date_range(x, y, freq='1T'))
.index.strftime('%Y/%m/%d %H:%M:%S')
.tolist())
timedf=pd.DataFrame([])
timedf['datetime']=l
timedf["Key"]=ck
fdf=fdf.append(timedf)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
