Holy Moly Holy Moly - 1 month ago 12
Python Question

adding datime.datetime and datetime.time

I am trying to add datetime.datetime and datetime.time to get one column. I was trying combine:

import datetime as dt
dt.datetime.combine(myDF['Date'].astype(dt.date), myDF['Time'].astype(dt.time))


but I get:

TypeError: combine() argument 1 must be datetime.date, not Series


and I was trying this:

myDF['Date'] + myDF['Time']


but I get

TypeError: unsupported operand type(s) for +: 'datetime.datetime' and 'datetime.time'


does anybody know, how I can combine my two colums?

Date Time
0 2011-08-08 00:00:00 08:10:00
1 2011-08-08 00:00:00 08:10:00
2 2011-08-08 00:00:00 08:10:00
3 2011-08-08 00:00:00 11:20:00
4 2011-08-08 00:00:00 12:25:00
5 2011-08-08 00:00:00 14:20:00

Answer Source

You are trying to combine whole columns, but datetime.combine() doesn't know how to be applied to separate columns.

Use the DataFrame.apply() method instead:

def combine_cols(row):
    return dt.datetime.combine(
        row['Date'].date(), row['Time'])

myDF.apply(combine_cols, axis=1)

axis=1 tells apply() to pass each row to the callable.

Demo:

>>> import pandas as pd
>>> import datetime as dt
>>> myDF = pd.DataFrame({
...     'Date': pd.Series([dt.datetime(2011, 8, 8)] * 6),
...     'Time': pd.Series([dt.time(8, 10), dt.time(8, 10), dt.time(8, 10), dt.time(11, 20), dt.time(12, 25), dt.time(14, 20)])
... })
>>> myDF
        Date      Time
0 2011-08-08  08:10:00
1 2011-08-08  08:10:00
2 2011-08-08  08:10:00
3 2011-08-08  11:20:00
4 2011-08-08  12:25:00
5 2011-08-08  14:20:00
>>> def combine_cols(row):
...     return dt.datetime.combine(
...         row['Date'].date(), row['Time'])
...
>>> myDF.apply(combine_cols, axis=1)
0   2011-08-08 08:10:00
1   2011-08-08 08:10:00
2   2011-08-08 08:10:00
3   2011-08-08 11:20:00
4   2011-08-08 12:25:00
5   2011-08-08 14:20:00
dtype: datetime64[ns]