python - 如何将 datetime.time() 对象转换为 datetime.datetime 对象 pandas

标签 python pandas python-datetime

import pandas as pd
import datetime
df = pd.DataFrame([{'st':datetime.datetime.strptime('21:00:00','%H:%M:%S').time(),'et':datetime.datetime.strptime('22:00:00','%H:%M:%S').time()}, {'st':datetime.datetime.strptime('1:00:00','%H:%M:%S').time(),'et':datetime.datetime.strptime('3:00:00','%H:%M:%S').time()}])


Out[183]: df
         et        st
0  22:00:00  21:00:00
1  03:00:00  01:00:00

我希望能够使用具有 datetime.datetime 对象和另外两个额外列的新字段来转换上述数据帧,例如此处包含任何虚拟日期并使用各自的时间行:

      et        st      sdate_time                edate_time
0  22:00:00  21:00:00   2018-01-01 21:00:00      2018-01-01 22:00:00  
1  03:00:00  01:00:00   2018-01-01 1:00:00       2018-01-01 3:00:00

我尝试过的方法是使用 apply 方法

df['et'].apply(lambda et: pd.datetime.combine(datetime.datetime.strptime('2018-01-01', '%Y-%m-%d').date(),et))

但事实证明数据帧可能非常巨大,我想在不使用 apply 方法的情况下对上述操作进行矢量化。

最佳答案

试试这个

date = str(datetime.datetime.strptime('2018-01-01', '%Y-%m-%d').date())

df['edate_time'] = pd.to_datetime(date + " " + df.et.astype(str))

       et          st            edate_time
0   22:00:00    21:00:00    2018-01-01 22:00:00
1   03:00:00    01:00:00    2018-01-01 03:00:00

关于python - 如何将 datetime.time() 对象转换为 datetime.datetime 对象 pandas,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52955534/

相关文章:

python - 猴子修补 'datetime' 产生奇怪的结果

python - datetime.strptime 格式化

Python 脚本知道它使用了多少内存

python - django 模板只显示不同的值

pandas - 如何在 vscode 中打印出 Pandas 数据帧

python - 在 python 中使用带宽方法进行投资组合再平衡

python - 将 2021-01-18T11 :18:10. 833876+00:00 转换为日期时间 python

python - 避免以前的文件

Python selenium webdriver - 无法一次通过 xpath 单击元素

python-3.x - 如何检查嵌套列表是否存在以及如果存在则取消嵌套?