Laura
Laura

Reputation: 1282

Summing two datetime columns

I have a datadframe with two columns, for example

A                B 
00:01:05         2018-10-10 23:58:10

and I want to get a third column C which is the sum of A + B

A                B                             C
00:01:05         2018-10-10 23:58:10           2018-10-10 23:59:15

If I do:

df['C']= df['A'] + df['B']

I get

cannot add DatetimeArray and DatetimeArray

Upvotes: 3

Views: 8189

Answers (2)

jezrael
jezrael

Reputation: 862511

Convert column A to timedeltas by to_timedelta and if necessary column B to to_datetime:

df = pd.DataFrame({'A':['00:01:05'],
                   'B':['2018-10-10 23:58:10']})

df['C'] = pd.to_timedelta(df['A']) + pd.to_datetime(df['B'])
print (df)
          A                    B                   C
0  00:01:05  2018-10-10 23:58:10 2018-10-10 23:59:15

If column A contains python times:

df['C'] = pd.to_timedelta(df['A'].astype(str)) + pd.to_datetime(df['B'])

Upvotes: 6

Sreeram TP
Sreeram TP

Reputation: 11907

This is your sample dataframe,

sample = pd.DataFrame()

sample['A'] = ['00:01:05']
sample['B'] = ['2018-10-10 23:58:10']

convert column B to pd.Timstamp and A to pd.Timedelta like this,

sample['B'] = pd.to_datetime(sample['B'])
sample['A'] = pd.to_timedelta(sample['A'], unit='m')

And then add the columns normally,

sample['C'] = sample['B'] + sample['A']

    A                    B                     C
0   00:01:05    2018-10-10 23:58:10     2018-10-10 23:59:15

Upvotes: 4

Related Questions