解析datetime64和datetime.time Python 3.6.5

时间:2018-08-20 10:57:03

标签: python python-3.x pandas datetime

  

我有两列,一列的类型为datetime64和datetime.time。的   第一列为日期,第二列为小时和分钟。一世   解析它们时遇到了麻烦:

Leistung_0011

       ActStartDateExecution ActStartTimeExecution
0             2016-02-17              11:00:00
10            2016-04-15              07:15:00
20            2016-06-10              10:30:00

Leistung_0011 ['Start_datetime'] = pd.to_datetime(Leistung_0011 ['ActStartDateExecution'.astype(str)+''+ Leistung_0011 ['ActStartTimeExecution']。astype(str))

ValueError: ('Unknown string format:', 'NaT 00:00:00')

1 个答案:

答案 0 :(得分:1)

您可以转换为str并加入空格,然后再传递给pd.to_datetime

df['datetime'] = pd.to_datetime(df['day'].astype(str) + ' ' + df['time'].astype(str))

print(df, df.dtypes, sep='\n')

#          day      time            datetime
# 0 2018-01-01  15:00:00 2018-01-01 15:00:00
# 1 2015-12-30  05:00:00 2015-12-30 05:00:00
# day         datetime64[ns]
# time                object
# datetime    datetime64[ns]
# dtype: object

设置

from datetime import datetime

df = pd.DataFrame({'day': ['2018-01-01', '2015-12-30'],
                   'time': ['15:00', '05:00']})

df['day'] = pd.to_datetime(df['day'])
df['time'] = df['time'].apply(lambda x: datetime.strptime(x, '%H:%M').time())

print(df['day'].dtype, type(df['time'].iloc[0]), sep='\n')

# datetime64[ns]
# <class 'datetime.time'>

包含秒的完整示例:

import pandas as pd
from io import StringIO

x = StringIO("""       ActStartDateExecution ActStartTimeExecution
0             2016-02-17              11:00:00
10            2016-04-15              07:15:00
20            2016-06-10              10:30:00""")

df = pd.read_csv(x, delim_whitespace=True)

df['ActStartDateExecution'] = pd.to_datetime(df['ActStartDateExecution'])
df['ActStartTimeExecution'] = df['ActStartTimeExecution'].apply(lambda x: datetime.strptime(x, '%H:%M:%S').time())
df['datetime'] = pd.to_datetime(df['ActStartDateExecution'].astype(str) + ' ' + df['ActStartTimeExecution'].astype(str))

print(df.dtypes)

ActStartDateExecution    datetime64[ns]
ActStartTimeExecution            object
datetime                 datetime64[ns]
dtype: object