修改Twitter返回日期格式仅显示月份(字母形式)及报错解决
Hey Steve, let's fix this issue step by step. The error you're seeing has two main causes, and we'll tackle them both to get the letter-form month you want.
First, let's break down what's wrong with your code:
df['date'] = np.array([((tweet.created_at.strftime('%Y-%B-%d::%H-%M')).month for tweet in tweets)])
Two critical problems here:
- When you run
strftime('%Y-%B-%d::%H-%M'), you get a string (like "2024-October-05::14-22"). Strings don't have a.monthattribute—this would throw an error even before the length mismatch issue pops up! - Wrapping the generator expression in
[]and converting it to a numpy array gives you an array containing one single generator object, not an array of month values. That's why you get theLength of values does not match length of indexerror: your array has length 1, but your DataFrame has far more rows.
The Fix: Get Letter-Form Months Correctly
You want the full month name (like "October")? Use strftime('%B') directly on the created_at datetime object. Here's the clean, working solution:
# Assuming `tweets` is your list of tweet objects, each with a datetime `created_at` property df['month'] = [tweet.created_at.strftime('%B') for tweet in tweets]
If you prefer using numpy (though it's not strictly necessary here), you can convert the list to an array first:
import numpy as np df['month'] = np.array([tweet.created_at.strftime('%B') for tweet in tweets])
Bonus: If created_at is a string (not a datetime)
Sometimes the Twitter API returns created_at as a raw string (like "Sun Oct 05 14:22:00 +0000 2024"). If that's your case, parse it to a datetime first before extracting the month:
from datetime import datetime df['month'] = [ datetime.strptime(tweet.created_at, '%a %b %d %H:%M:%S %z %Y').strftime('%B') for tweet in tweets ]
Quick Tips:
- Use
'%b'instead of'%B'if you want abbreviated months (e.g., "Oct" instead of "October") - Always make sure you're calling datetime methods on actual datetime objects, not strings
- List comprehensions are ideal here because they generate a list with exactly one value per tweet, perfectly matching your DataFrame's row count
内容的提问来源于stack exchange,提问作者Steve Dino

