how to convert a datetime.time() object to datetime.datetime object pandas

試著忘記壹切 提交于 2021-01-03 05:19:33

问题


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:

      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

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 .


回答1:


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



回答2:


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



回答3:


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.

I've seen workarounds for the label, using import matplotlib.dates as mdates but still not the best way.



来源:https://stackoverflow.com/questions/52955534/how-to-convert-a-datetime-time-object-to-datetime-datetime-object-pandas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!