Home > Back-end >  Dataframe - How to access datetime properties?
Dataframe - How to access datetime properties?

Time:01-06

I want to acces datetime object properties like .seconds(), .minutes() etc. Datetime values are stored in Dataframe in column DateTime. I need this acces so I can use np.where() on these values like in a following example but When I run this code I am getting AttributeError: 'Series' object has no attribute 'minutes':

if interval_higher_str == 'seconds':
    occurances = np.where(price_df_lower_interval['DateTime'].second == interval_higher)
elif interval_higher_str == 'minutes':
    occurances = np.where(price_df_lower_interval['DateTime'].minute() == interval_higher and price_df_lower_interval['DateTime'].second() == 0)
elif interval_higher_str == 'hours':
    occurances = np.where(price_df_lower_interval['DateTime'].hour() == interval_higher and price_df_lower_interval['DateTime'].minute() == 0 and price_df_lower_interval['DateTime'].second() == 0)
elif interval_higher_str == 'day':
    occurances = np.where(price_df_lower_interval['DateTime'].hour() == trade_start_hour and price_df_lower_interval['DateTime'].minute() == 0 and price_df_lower_interval['DateTime'].second() == 0)
elif interval_higher_str == 'week':
    occurances = np.where(price_df_lower_interval['DateTime'].weekday() == 0 and price_df_lower_interval['DateTime'].hour() == trade_start_hour and price_df_lower_interval['DateTime'].minute() == trade_start_minute and price_df_lower_interval['DateTime'].second() == 0)
elif interval_higher_str == 'month':
    occurances = np.where(price_df_lower_interval['DateTime'].day() == 1 and price_df_lower_interval['DateTime'].hour() == trade_start_hour and price_df_lower_interval['DateTime'].minute() == trade_start_minute and price_df_lower_interval['DateTime'].second() == 0)
elif interval_higher_str == 'year':
    occurances = np.where(price_df_lower_interval['DateTime'].month() == 1 and price_df_lower_interval['DateTime'].day() == 1 and price_df_lower_interval['DateTime'].hour() == trade_start_hour and price_df_lower_interval['DateTime'].minute() == trade_start_minute and price_df_lower_interval['DateTime'].second() == 0)

I know I can loop through the dataframe and either create an auxilliary columns which will store each parameter, or just loop through it and save index where condition was met to the list, but I can see that except from being extremly slow I have a feeling that it will be overly complicated.

How can I achieve the same result my code should give but without looping through the dataframe?

CodePudding user response:

You can access the datetime properties with .dt

df = pd.DataFrame({"str_date": ["2023-01-01 12:13:21", "2023-01-02 13:10:24 "]})
df["date"] = pd.to_datetime(df["str_date"], format="%Y-%m-%d %H:%M:%S")
df.date.dt.hour
df.date.dt.minute
df.date.dt.second
  • Related