Home > Mobile >  Checking a datetime index value
Checking a datetime index value

Time:07-20

Never figured this one out.

A datetime index in a dataframe is selected by df.loc['2022-07-18 15:15:00'] or iloc or whatever but how can I perform a conditional check on the time in an datetime to create a column value for a specific time? i.e.

if index.time = '***16:00:00':
  df['end'] = True

I don't know how to use wildcards in this instance either.

CodePudding user response:

Assuming a datetime index, you can use:

df['end'] = df.index == '16:00:00'  # also works with '16:00'

example output:

                     col    end
2022-07-20 04:52:06    0  False
2022-07-20 10:16:24    1  False
2022-07-20 10:41:42    2  False
2022-07-20 16:00:00    3   True
2022-07-20 19:07:42    4  False

reproducible input:

from pandas import Timestamp
df = pd.DataFrame({'col': {Timestamp('2022-07-20 04:52:06'): 0,
                           Timestamp('2022-07-20 10:16:24'): 1,
                           Timestamp('2022-07-20 10:41:42'): 2,
                           Timestamp('2022-07-20 16:00:00'): 3,
                           Timestamp('2022-07-20 19:07:42'): 4}})

CodePudding user response:

Use dt to subset the data frame df as follows:

df[(df.time.dt.hour==16) & (df.time.dt.minute==0) & (df.time.dt.second==0)]

as outlines in the enter image description here

and observe the sub-frame:

enter image description here

  • Related