Home > Blockchain >  Getting a new datatime by offsetting a lapse in the unit of second from a fixed constant datetime
Getting a new datatime by offsetting a lapse in the unit of second from a fixed constant datetime

Time:12-17

Given a fix datetime '2019-01-15 7:00:00', the objective is to create a new datatime based on an offset value under the column (offset, '') . The unit of the offset value is in term of second.

The expected output is given in the column time

      (offset,'' )  time
0             0  2019-01-15 7:00:00
1            20  2019-01-15 7:00:20
2            40
3            60  2019-01-15 7:01:00
4            80
...         ...
4315      86300
4316      86320
4317      86340
4318      86360
4319      86380
[4320 rows x 1 columns]

My impression this can be achieved via

pd.to_datetime(['2019-01-15 7:00:00']).add(pd.to_timedelta(df[('lapse','')],unit='s'))

However, the compiler return an error

AttributeError: 'DatetimeIndex' object has no attribute 'add'

May I know how to resolve issue?

The full code to reproduce the above issue is as below

import numpy as np
import pandas as pd

np.random.seed(0)
increment=20
max_val=86400
# Elapse unit in second
aran=np.arange(0,max_val,increment).astype(int)
df=pd.DataFrame(aran,columns=[('lapse','')])

df['time']=pd.to_datetime(['2019-01-15 7:00:00']).add(pd.to_timedelta(df[('lapse','')],unit='s'))

CodePudding user response:

Pass your timestamp as a str instead of list and use the operator:

df['time'] = pd.to_datetime('2019-01-15 7:00:00')   pd.to_timedelta(df[('lapse','')],unit='s')

[out]

      (lapse, )                time
0             0 2019-01-15 07:00:00
1            20 2019-01-15 07:00:20
2            40 2019-01-15 07:00:40
3            60 2019-01-15 07:01:00
4            80 2019-01-15 07:01:20
...         ...                 ...
4315      86300 2019-01-16 06:58:20
4316      86320 2019-01-16 06:58:40
4317      86340 2019-01-16 06:59:00
4318      86360 2019-01-16 06:59:20
4319      86380 2019-01-16 06:59:40

[4320 rows x 2 columns]

CodePudding user response:

Use to_datetime with origin and unit='s' parameters:

df['time'] = pd.to_datetime(df[('lapse','')], origin='2019-01-15 7:00:00', unit='s')
print (df)
      (lapse, )                time
0             0 2019-01-15 07:00:00
1            20 2019-01-15 07:00:20
2            40 2019-01-15 07:00:40
3            60 2019-01-15 07:01:00
4            80 2019-01-15 07:01:20
        ...                 ...
4315      86300 2019-01-16 06:58:20
4316      86320 2019-01-16 06:58:40
4317      86340 2019-01-16 06:59:00
4318      86360 2019-01-16 06:59:20
4319      86380 2019-01-16 06:59:40

[4320 rows x 2 columns]
  • Related