birdalugur
birdalugur

Reputation: 191

How to assign hour information to a Pandas Timestamp series?

I have a pandas Timestamp series. I also have a datetime.time series. I just want to change the clock part of the timestamp. and I will get these values ​​from the datetime.time series. What is the easiest way to do this?

A code like this gives me the result I want:

for i in range(len(df)):
    result= df.date[i].replace(hour=df.time[i].hour,minute=df.time[i].minute,second=df.time[i].second)
    print(result)
2018-09-06 18:00:00
2018-09-06 18:00:01
2018-09-06 18:00:02
2018-09-06 18:00:03
2018-09-06 18:00:04

Data-related information:

>>>df

Output:

|   | time     | date       |
|---|----------|------------|
| 0 | 18:00:00 | 2018-09-06 |
| 1 | 18:00:01 | 2018-09-06 |
| 2 | 18:00:02 | 2018-09-06 |
| 3 | 18:00:03 | 2018-09-06 |
| 4 | 18:00:04 | 2018-09-06 |
>>>df.dtypes

Output:

time            object
date    datetime64[ns]
dtype: object
>>>df.date[0]
>>>df.time[0]

Output:

Timestamp('2018-09-06 00:00:00')
datetime.time(18, 0)

But are there such easy methods?

df.date.Example_Function(df.time)

or

df.date.time=df.time

Upvotes: 2

Views: 134

Answers (1)

jezrael
jezrael

Reputation: 862641

Use to_timedelta with DataFrame.pop for extract column and because python times also convert to strings:

df['date'] += pd.to_timedelta(df.pop('time').astype(str))
print (df)
                 date
0 2018-09-06 18:00:00
1 2018-09-06 18:00:01
2 2018-09-06 18:00:02
3 2018-09-06 18:00:03
4 2018-09-06 18:00:04

Upvotes: 1

Related Questions