所以我基本上統計了一個頻道里所有的訊息。我還想統計每天的訊息數。我知道 message.created_at 回傳一個日期時間,但我如何計算一個日期出現在這個串列中的次數?
這是我當前的代碼:
count = 0
async for message in channel.history(limit=None):
count = 1
print(message.created_at)
我試著這樣做:
count = 0
async for message in channel.history(limit=None):
count = 1
dates.append(message.created_at)
print(dates.count(dates[0]))
但這只會回傳“1”(而串列中有更多不同的日子)
這是我關于stack overflow的第一篇文章,請勿中毒,歡迎反饋!
uj5u.com熱心網友回復:
您的代碼不是在計算某個日期的訊息數量,而是在計算某個datetime.datetime物件上的訊息,該物件代表一個特定的時間點(根據 API 的精度,可能精確到微秒)。
這是因為message.created_at回傳訊息的時間和日期,您可能想要的是message.created_at.date()(請參閱日期時間檔案)。
如果你想知道每個日期有多少條訊息,你可以使用字典來計算:
messages_per_date = {} # empty dictionary
async for message in channel.history(limit=None):
message_date = message.created_at.date()
# Add the date to the dictionary if necessary
if message_date not in messages_per_date:
messages_per_date[message_date] = 0
# Increment the number of messages on that date
messages_per_date[message_date] = 1
# Print the number of messages today
print(messages_per_date[datetime.date.today()])
您可以使用collections.defaultdict來顯著縮短代碼:
import collections
# This creates a dictionary in which the default value is zero
messages_per_date = collections.defaultdict(int)
async for message in channel.history(limit=None):
# Now the values can be incremented without checking the key
messages_per_date[message.created_at.date()] = 1
print(messages_per_date[datetime.date.today()])
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/537892.html
