如何在Pandas中从UTC时间序列获取星期几?遇类型错误求助
Hey there! I see the issue you're running into—let's break this down and fix it quickly.
Why the Error Happens
The datetime.fromtimestamp() function only works with single numeric values, but you're passing an entire Pandas Series (df['utc_time']/1000) to it. Pandas can't convert the whole Series to a single int, hence the TypeError: cannot convert the series to <class 'int'>.
Solution 1: Use Pandas' Built-in Vectorized Operations (Recommended)
Pandas has optimized methods for handling datetime conversions on entire Series—this is way faster than looping through each element, especially with large datasets.
import pandas as pd # Convert millisecond timestamp to datetime object (vectorized operation) df['utc_time'] = pd.to_datetime(df['utc_time'], unit='ms') # Extract full weekday name (e.g., "Monday", "Tuesday") df['Week_Day'] = df['utc_time'].dt.day_name()
unit='ms'tells Pandas your timestamp is in milliseconds (your 13-digit value is a clear sign of this).dt.day_name()returns the full weekday name, exactly likestrftime("%A")does. For older Pandas versions (pre-1.1.0), usedt.weekday_nameinstead.
Solution 2: Use apply() for Element-wise Processing
If you specifically want to use the datetime module, you can use apply() to run the conversion on each individual value in the Series:
from datetime import datetime # Apply the conversion to each element in the Series df['Week_Day'] = df['utc_time'].apply(lambda x: datetime.fromtimestamp(x/1000).strftime("%A"))
apply()iterates over every value indf['utc_time'], passes each single int valuexto the lambda function, and runs the timestamp conversion on it. This avoids the TypeError because we're no longer passing a Series todatetime.fromtimestamp().
Quick Test to Verify
Let's confirm with your sample timestamp:
import pandas as pd from datetime import datetime # Sample data with your timestamp test_df = pd.DataFrame({'utc_time': [1536444323321]}) # Method 1 test_df['datetime'] = pd.to_datetime(test_df['utc_time'], unit='ms') test_df['weekday_1'] = test_df['datetime'].dt.day_name() # Method 2 test_df['weekday_2'] = test_df['utc_time'].apply(lambda x: datetime.fromtimestamp(x/1000).strftime("%A")) print(test_df)
Both methods will return Monday (your sample timestamp converts to 2018-09-09 UTC, which is a Monday).
内容的提问来源于stack exchange,提问作者John

