python添加时间戳,Python:向熊猫时间戳添加小时

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])

type(df['Hour'][0])

>>> type(df['TradingDate'])

>>> type(df['Hour'])

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.

解决方案

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值