简体   繁体   English

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

[英]how to convert a datetime.time() object to datetime.datetime object pandas

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

I would like to be able to convert the above dataframe with new fields having datetime.datetime objects with two other extra columns such as here having any dummy date in it and using the time from their respective rows:我希望能够将上述数据框转换为具有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

The approach I have tried is using apply method我尝试过的方法是使用 apply 方法

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

but turns out that the dataframe could be really huge and I would like to vectorize the above operation without the apply method .但事实证明,数据帧可能非常庞大,我想在不使用 apply 方法的情况下对上述操作进行矢量化。

Try this尝试这个

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

Try:尝试:

df.assign(sdate_time=pd.to_datetime(df['et'], format='%H:%M:%S'), 
          edate_time=pd.to_datetime(df['st'], format='%H:%M:%S'))

Output:输出:

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

Is there no better way of doing this than to assign a random date?没有比分配随机日期更好的方法了吗?

I have matplotlib version '3.3.1' and still face this issue of not being able to plot a datetime.time object for which I do not need a date but only the 24 hours of a day.我有 matplotlib 版本“3.3.1”,但仍然面临无法绘制不需要日期而只需要一天 24 小时的 datetime.time 对象的问题。

I've seen workarounds for the label, using import matplotlib.dates as mdates but still not the best way.我已经看到了标签的解决方法,使用import matplotlib.dates as mdates但仍然不是最好的方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM