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

如何在Pandas中从UTC时间序列获取星期几?遇类型错误求助

Fixing TypeError When Converting Millisecond Timestamp to Weekday in Pandas

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'>.

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 like strftime("%A") does. For older Pandas versions (pre-1.1.0), use dt.weekday_name instead.

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 in df['utc_time'], passes each single int value x to the lambda function, and runs the timestamp conversion on it. This avoids the TypeError because we're no longer passing a Series to datetime.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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.12 04:25:50