【问题标题】:Datetime comparison in PythonPython中的日期时间比较
【发布时间】:2020-03-19 21:52:42
【问题描述】:

我有一个日期时间列,需要查找时间在任何一天的 9:30 到 17:00 之间的那些记录。我不关心日期,但需要根据时间过滤数据。

2018-12-28 10:53:24.950
2018-12-28 10:53:55.010
2019-01-02 16:48:31.593
2019-01-02 16:48:31.593
2019-01-02 16:48:31.593

我正在使用以下命令来提取小时数。

df1['hour_of_timestamp'] = df1['User_date'].dt.hour

【问题讨论】:

标签: python datetime comparison


【解决方案1】:

Pandas 确实有一个内置方法 between_time() 来选择特定时间段内的行,但它只适用于日期时间对象是索引(或最近的列)。

由于您已经有一个 datetime 列,您可以像这样提取行(改编自 here 的示例):

import pandas as pd

data = [["20090102 04:51:00", 89.9900, 89.9900, 89.9900, 89.9900, 100], ["20190102 05:36:00", 90.0100, 90.0100, 90.0100, 90.0100, 200], ["20090102 05:44:00", 90.1400, 90.1400, 90.1400, 90.1400, 100], ["20090102 05:50:00", 90.0500, 90.0500, 90.0500, 90.0500, 500], ["20090102 05:56:00", 90.1000, 90.1000, 90.1000, 90.1000, 300], ["20090102 05:57:00", 90.1000, 90.1000, 90.1000, 90.1000, 200]]

# Building sample dataframe with Datetime column
df = pd.DataFrame(data)
df.columns = ["Datetime", "1", "2", "3", "4", "5"]
df['Datetime'] = pd.to_datetime(df['Datetime'], format="%Y%m%d %H:%M:%S")

# Extract rows with datetime matching index range
print(df.set_index("Datetime").between_time('5:30:00', '5:45:00'))

这只是输出时间范围之间的记录。

                         1      2      3      4    5
Datetime                                            
2019-01-02 05:36:00  90.01  90.01  90.01  90.01  200
2009-01-02 05:44:00  90.14  90.14  90.14  90.14  100

【讨论】:

    【解决方案2】:

    您可以使用d = datetime.datetime.fromisoformat(date_str) 解析您的日期。然后您可以检查d.hourd.minute 来做出决定。

    【讨论】:

      【解决方案3】:

      如果您的日期始终采用 YYYY-MM-DD 格式,那么为什么不直接对字符串进行切片以获取时间:

      time_str = date_str[10:].strip()
      

      然后,您只需使用 sorted(time_list) 对时间列表进行排序,然后查找 9:30 到 17:00 之间的时间。

      【讨论】:

      • 使用前是否需要转换列的数据类型。 df1['new'] = df1['User_date'].str[10:] 给出错误,因为 User_date 是我唯一的列
      • @SunilRaperia 是的,它需要是一个字符串才能切片。
      猜你喜欢
      • 2012-01-20
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多