在python熊猫中将时间对象转换为日期时间格式

时间:2018-11-25 17:59:40

标签: python python-3.x pandas datetime dataframe

我有一个列名称为 DateTime 的数据集,其数据类型为 object

df['DateTime'] = pd.to_datetime(df['DateTime'])

我已使用上面的代码将其转换为 datetime 格式,然后在列中进行了拆分,以分别具有 Date Time

df['date'] = df['DateTime'].dt.date
df['time'] = df['DateTime'].dt.time

但是在拆分之后,格式更改为对象类型,并且在将其转换为日期时间时,它显示了 time 列名称的错误,如下所示: TypeError:无法转换为日期时间

如何在时间

中将其转换为日期时间格式

2 个答案:

答案 0 :(得分:0)

您可以在zip的列表理解中使用combine

df = pd.DataFrame({'DateTime': ['2011-01-01 12:48:20', '2014-01-01 12:30:45']})
df['DateTime'] = pd.to_datetime(df['DateTime'])

df['date'] = df['DateTime'].dt.date
df['time'] = df['DateTime'].dt.time

import datetime
df['new'] = [datetime.datetime.combine(a, b) for a, b in zip(df['date'], df['time'])]
print (df)

             DateTime        date      time                 new
0 2011-01-01 12:48:20  2011-01-01  12:48:20 2011-01-01 12:48:20
1 2014-01-01 12:30:45  2014-01-01  12:30:45 2014-01-01 12:30:45

或转换为字符串,连接在一起然后再次转换:

df['new'] = pd.to_datetime(df['date'].astype(str) + ' ' +df['time'].astype(str))
print (df)
             DateTime        date      time                 new
0 2011-01-01 12:48:20  2011-01-01  12:48:20 2011-01-01 12:48:20
1 2014-01-01 12:30:45  2014-01-01  12:30:45 2014-01-01 12:30:45

但是如果使用floor来删除时间并将时间转换为时间增量,则仅使用+

df['date'] = df['DateTime'].dt.floor('d')
df['time'] = pd.to_timedelta(df['DateTime'].dt.strftime('%H:%M:%S'))

df['new'] = df['date'] + df['time']
print (df)

             DateTime       date     time                 new
0 2011-01-01 12:48:20 2011-01-01 12:48:20 2011-01-01 12:48:20
1 2014-01-01 12:30:45 2014-01-01 12:30:45 2014-01-01 12:30:45

答案 1 :(得分:0)

  

如何将其转换回日期时间格式的时间列

似乎存在误解。熊猫d = {(1, 'a', 'b') : 2, (4, 'c', 'd'):5} # Check for existence of any key matching criteria any(pair == ('a', 'b') for key in d for pair in zip(key, key[1:])) # True # Filter out keys/values matching criteria {k: v for k, v in d.items() if any(p == ('a', 'b') for p in zip(k, k[1:]))} # {(1, 'a', 'b'): 2} 系列必须包括日期和时间部分。这是不可谈判的。您可以简单地使用datetime而不指定日期,而使用默认的pd.to_datetime日期:

1900-01-01

或使用其他日期组件,例如今天的日期:

# date from jezrael

print(pd.to_datetime(df['time'], format='%H:%M:%S'))

0   1900-01-01 12:48:20
1   1900-01-01 12:30:45
Name: time, dtype: datetime64[ns]

或者从您的today = pd.Timestamp('today').strftime('%Y-%m-%d') print(pd.to_datetime(today + ' ' + df['time'].astype(str))) 0 2018-11-25 12:48:20 1 2018-11-25 12:30:45 Name: time, dtype: datetime64[ns] date系列中重新组合:

time
相关问题