python - 在 python pandas 中将时间对象转换为日期时间格式

标签 python python-3.x pandas datetime dataframe

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

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

我已使用上面的代码转换为日期时间格式,然后在列中进行拆分以分别显示日期时间

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

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

如何将时间列转换为日期时间格式

最佳答案

您可以使用combine使用 zip 进行列表理解:

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

关于python - 在 python pandas 中将时间对象转换为日期时间格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53470304/

相关文章:

python - 从稀疏日期时间索引获取范围

python - OpenCV 概率霍夫线变换使用 C++ 和 Python 给出不同的结果?

python - Python 的 a, b = b, a 是如何工作的?

python - 在Python中定义默认类属性?

pandas - 如何计算numpy中一维数组的移动(或滚动,如果你愿意)百分位数/分位数?

python - 查找索引行和数据框中每一行之间的公共(public)非空列

python - 使用 Python 同时下载一个文件的多个部分?

python - 合并数据框列表以创建一个数据框

python - 从列表中填充字典

python-3.x - 使用预训练的gensim Word2vec嵌入以及keras中的数据集