Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Adding hours to pandas timestamp

I read a csv file into pandas dataframe df and I get the following:

df.columns
Index([u'TDate', u'Hour', u'SPP'], dtype='object')
>>> type(df['TDate'][0])
<class 'pandas.tslib.Timestamp'>

type(df['Hour'][0])
<type 'numpy.int64'>

>>> type(df['TradingDate'])
<class 'pandas.core.series.Series'>
>>> type(df['Hour'])
<class 'pandas.core.series.Series'>

Both the Hour and TDate columns have 100 elements. I want to add the corresponding elements of Hour to TDate.

I tried the following:

import pandas as pd
from datetime import date, timedelta as td
z3 = pd.DatetimeIndex(df['TDate']).to_pydatetime() + td(hours = df['Hour'])

But I get error as it seems td doesn't take array as argument. How do I add each element of Hour to corresponding element of TDate.

like image 204
Zanam Avatar asked Jun 21 '16 22:06

Zanam


People also ask

How do I add hours to a datetime?

Use the timedelta() class from the datetime module to add hours to datetime, e.g. result = dt + timedelta(hours=10) . The timedelta class can be passed a hours argument and adds the specified number of hours to the datetime.

How do I add a timestamp to pandas DataFrame?

Example 1: Timestamps with to_datetime. Here we are converting the CSV file into a dataframe using pandas. DataFrame() method after reading the contents of the file using pandas. read_csv(), the timestamps column from the data Dataframe is given as an argument in the to_datetime() for it to be converted into DateTime.


1 Answers

I think you can add to column TDate column Hour converted to_timedelta with unit='h':

df = pd.DataFrame({'TDate':['2005-01-03','2005-01-04','2005-01-05'],
                   'Hour':[4,5,6]})

df['TDate'] = pd.to_datetime(df.TDate)
print (df)
   Hour      TDate
0     4 2005-01-03
1     5 2005-01-04
2     6 2005-01-05

df['TDate'] +=  pd.to_timedelta(df.Hour, unit='h')
print (df)
   Hour               TDate
0     4 2005-01-03 04:00:00
1     5 2005-01-04 05:00:00
2     6 2005-01-05 06:00:00
like image 197
jezrael Avatar answered Oct 21 '22 22:10

jezrael