Houda L
Houda L

Reputation: 85

How to convert datetime.time columns in dataframe to string

I've been struggling to convert two columns in a pandas. The frame contains many columns, and 2 columns with dates: 'datelog'(is a date) and 'Timeofday' (is a time). The column datelog is a string. The column Timeofday is a datetime.time() format. The dateframe display is as folows:

     datelog Timeofday
0  30-APR-15  14:15:43
1  30-APR-15  14:16:13
2  30-APR-15  14:16:43
3  30-APR-15  14:17:13
4  30-APR-15  14:17:43
5  30-APR-15  14:18:13
6  30-APR-15  14:18:43
7  30-APR-15  14:19:13
8  30-APR-15  14:19:43
9  30-APR-15  14:20:13

My goal is to concatenate these two column to use them as a index for a timeseries. Can somebody point me in the right direction?

Upvotes: 1

Views: 5255

Answers (2)

jezrael
jezrael

Reputation: 863531

You can use to_datetime and to_timedelta if want DatetimeIndex. If not, use ysearka solution:

df.index = pd.to_datetime(df.datelog) + pd.to_timedelta(df.Timeofday)

print (df.index)
DatetimeIndex(['2015-04-30 14:15:43', '2015-04-30 14:16:13',
               '2015-04-30 14:16:43', '2015-04-30 14:17:13',
               '2015-04-30 14:17:43', '2015-04-30 14:18:13',
               '2015-04-30 14:18:43', '2015-04-30 14:19:13',
               '2015-04-30 14:19:43', '2015-04-30 14:20:13'],
              dtype='datetime64[ns]', freq=None)

Upvotes: 2

ysearka
ysearka

Reputation: 3855

I think you can use something like this to create your index:

df.index = df['datelog'] + ' ' + df['Timeofday'].astype(str)

Upvotes: 2

Related Questions