You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何基于分钟筛选Python 3中的datetime列表?

Solution for Filtering Datetimes by Minute Value

Hey there! Let's get that datetime filtering sorted out for you. You want to keep only the entries where the minute is 00, 20, or 40—here's a clean, straightforward way to do it:

First, instead of trying to exclude minutes like 10, 30, 50, it's simpler to check if the minute falls into your allowed set (0, 20, 40). We can also clean up the loop to avoid clunky index-based iteration, making the code more readable.

Working Code Example

import datetime

# Note: Adjusted to a list (sets don't preserve order; convert to a set later if needed)
first_datetime = [
    "2019-08-08 14:00:00",
    "2019-08-08 14:10:00",
    "2019-08-08 14:20:00",
    "2019-08-08 14:30:00",
    "2019-08-08 14:40:00",
    "2019-08-08 14:50:00",
    "2019-08-08 15:00:00"
]

new_datetime_list = []
# Define the minutes we want to retain
allowed_minutes = {0, 20, 40}

for dt_string in first_datetime:
    # Convert string to a datetime object to access minute value
    dt_object = datetime.datetime.strptime(dt_string, '%Y-%m-%d %H:%M:%S')
    # Check if the minute is in our allowed set
    if dt_object.minute in allowed_minutes:
        new_datetime_list.append(dt_string)

# Output the filtered result
print(new_datetime_list)

Key Details:

  • We use datetime.datetime.strptime() to convert each string into a proper datetime object, which lets us directly access the minute attribute.
  • The allowed_minutes set makes membership checks fast and clean—no messy multiple or conditions required.
  • Iterating directly over items in first_datetime (instead of using indexes) makes the code easier to read and maintain.

Bonus: If You Need Datetime Objects Instead of Strings

If you want new_datetime_list to store actual datetime objects (not strings), just modify the append line to:

new_datetime_list.append(dt_object)

And if your original first_datetime is a set (not a list), the loop will work exactly the same way—sets are fully iterable.

内容的提问来源于stack exchange,提问作者Buster3650

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.06 12:42:30