Dataframe -如何访问datetime属性?



我想访问datetime对象属性,如.seconds(),.minutes()等。Datetime值存储在DataframeDateTime列中。我需要这个访问,所以我可以在这些值上使用np.where(),就像下面的例子一样,但是当我运行这段代码时,我得到了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)

我知道我可以循环遍历数据框架,创建一个辅助列来存储每个参数,或者只是循环遍历它并将满足条件的索引保存到列表中,但我可以看到,除了非常慢之外,我有一种感觉,它将过于复杂。

如何实现相同的结果我的代码应该给出但不遍历数据框架?

您可以使用.dt访问datetime属性

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

最新更新