1

I have a dataframe with two time columns : df['START TIME'] and df['END TIME']

Both these columns have datetime.time values or nan(float). I want to go row by row in both these columns and check, if the value is datetime.time, then floor it, otherwise pass.

This is the command I wrote in loop to floor the time :

df.loc[0,'START TIME'].dt.floor()

This gives an Attribute error :

AttributeError: 'datetime.time' object has no attribute 'dt'

When I check the type of df.loc[0,'START TIME'], it says datetime.time

In[116]: type(df.loc[0,'START TIME'])
Out[116]: datetime.time

I need to convert time like the following :

if time = 22:05:29, then new_time = 22:00:00
if time = 22:26:32, then new_time = 22:00:00
if time = 22:31:17, then new_time = 23:00:00

Where am I going wrong? any help would be much appreciated!

Soumya Pandey
  • 321
  • 3
  • 19
  • Does this answer your question? [Timestamp object has no attribute dt](https://stackoverflow.com/questions/62803633/timestamp-object-has-no-attribute-dt) – G. Anderson May 12 '22 at 17:20
  • @G.Anderson Hello, thanks for responding :) df.loc[0,'START TIME'].floor() gives an attribute error again : 'datetime.time' object has no attribute 'floor' – Soumya Pandey May 12 '22 at 17:25
  • 1
    It's difficult to help diagnose without seeing a sample of your input data, but rather than operating row-by-row with `.loc[]`, the `.dt` accessor is useful for operating on a whole column or series at once. What about `df['START TIME'].dt.floor(freq='H')`? It will automatically skip `NaN/NaT` entries – G. Anderson May 12 '22 at 17:37

2 Answers2

2

You have python's datetime.time in your column. This is not compatible with Pandas datetime, that's why you cannot use dt accessor. You can keep it as python's datetime.time and use the time's function.

df['START TIME'].transform(lambda x: x.replace(minute=0, second=0))

Or convert it to Panda's timedelta64. This is probably easier for later operations.

(pd.to_timedelta(
    df['START TIME'].transform(lambda x: x.strftime('%H:%M:%S'))
).dt.floor(freq='H')
Emma
  • 8,518
  • 1
  • 18
  • 35
1

You can do a lambda function like this:

df['START TIME'] = df['START TIME'].apply(lambda x: check_floor(x))

Then you create your function check_floor(x) with the type check or nunpy.isnan and your floor function in case is true return the new value or else return the value as is. This answer here will help with the type detection. Detect if a variable is a datetime object