添加时间到达日期

时间:2018-05-07 08:20:31

标签: python-3.x pandas datetime

如何添加日期和时间?我有3列如下:

kickoffDate =['8/6/2017','8/6/2017','8/6/2017'] kickoffTime = ['15:00:00','15:00:00','15:00:00'] time =['51:48:00','86:05:00','10:04']

这种情况下的时间是mm:ss:00格式。 我想将这三列结合起来创建一个名为“eventdatetime'”的新列。 我对eventdatetime的期望是 eventdatetime = [06-08-2017 15:51:48,06-08-2017 16:26:05,06-08-2017 15:10:04]。 我怎样才能做到这一点? 我可以使用以下公式组合前两个:

DateTime1 =data['kickoffDate']+' '+ data ['kickoffTime']

任何人都可以提供建议吗? 感谢

1 个答案:

答案 0 :(得分:1)

根据您的编辑,您需要做的是:

import pandas as pd

kickoffDate =['8/6/2017','8/6/2017','8/6/2017']
kickoffTime = ['15:00:00','15:00:00','15:00:00']
time = ['51:48:00','86:05:00','10:04']

df = pd.DataFrame({'kickoffDate': kickoffDate,
                   'kickoffTime': kickoffTime,
                   'time': time})

df['kickoffDate'] = pd.to_datetime(df['kickoffDate'])
df['kickoffTime'] = pd.to_timedelta(df['kickoffTime'])
df['time'] = df['time'].apply(lambda x: pd.to_timedelta('{} minutes {} seconds'.format(*x.split(':')[:2])))

df['eventdatetime'] = df['kickoffDate'] + df['kickoffTime'] + df['time']

df
#  kickoffDate kickoffTime     time       eventdatetime
#0  2017-08-06    15:00:00 00:51:48 2017-08-06 15:51:48
#1  2017-08-06    15:00:00 01:26:05 2017-08-06 16:26:05
#2  2017-08-06    15:00:00 00:10:04 2017-08-06 15:10:04