Python datetime获取月份报错:TypeError: 'getset_descriptor'对象不可调用
问题描述
我有一个包含datetime列的DataFrame,该列存储的是从epoch开始的毫秒数。我用lambda函数成功获取了星期几(周一为0),但获取月份时触发错误:TypeError: 'getset_descriptor' object is not callable。
相关代码
from datetime import date from datetime import time from datetime import datetime # 获取星期几(周一为0) df2['week_day'] = df2['datetime'].apply(lambda x: datetime.weekday(datetime.fromtimestamp(x / 1000))) # 正常运行 print ('converted datetime to weekday') df2 df2['Month'] = df2['datetime'].apply(lambda x: datetime.month(datetime.fromtimestamp(x / 1000))) # 运行出错 #pd.DatetimeIndex(df2['datetime']).month df2
完整错误信息
TypeError Traceback (most recent call last) Input In [16], in <cell line: 9>() 7 print ('converted datetime to weekday') 8 df2 ----> 9 df2['Month'] = df2['datetime'].apply(lambda x: datetime.month(datetime.fromtimestamp(x / 1000))) 10 #pd.DatetimeIndex(df2['datetime']).month 11 df2 File C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\series.py:4433, in Series.apply(self, func, convert_dtype, args, **kwargs) 4323 def apply( 4324 self, 4325 func: AggFuncType, (...) 4328 **kwargs, 4329 ) -> DataFrame | Series: 4330 """ 4331 Invoke function on values of Series. 4332 (...) 4431 dtype: float64 4432 """ -> 4433 return SeriesApply(self, func, convert_dtype, args, kwargs).apply() File C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py:1082, in SeriesApply.apply(self) 1078 if isinstance(self.f, str): 1079 # if we are a string, try to dispatch 1080 return self.apply_str() -> 1082 return self.apply_standard() File C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\apply.py:1137, in SeriesApply.apply_standard(self) 1131 values = obj.astype(object)._values 1132 # error: Argument 2 to "map_infer" has incompatible type 1133 # "Union[Callable[..., Any], str, List[Union[Callable[..., Any], str]], 1134 # Dict[Hashable, Union[Union[Callable[..., Any], str], 1135 # List[Union[Callable[..., Any], str]]]]]"; expected 1136 # "Callable[[Any], Any]" -> 1137 mapped = lib.map_infer( 1138 values, 1139 f, # type: ignore[arg-type] 1140 convert=self.convert_dtype, 1141 ) 1143 if len(mapped) and isinstance(mapped[0], ABCSeries): 1144 # GH#43986 Need to do list(mapped) in order to get treated as nested 1145 # See also GH#25959 regarding EA support 1146 return obj._constructor_expanddim(list(mapped), index=obj.index) File C:\ProgramData\Anaconda3\lib\site-packages\pandas\_libs\lib.pyx:2870, in pandas._libs.lib.map_infer() Input In [16], in <lambda>(x) 7 print ('converted datetime to weekday') 8 df2 ----> 9 df2['Month'] = df2['datetime'].apply(lambda x: datetime.month(datetime.fromtimestamp(x / 1000))) 10 #pd.DatetimeIndex(df2['datetime']).month 11 df2 TypeError: 'getset_descriptor' object is not callable
错误原因
datetime.weekday()是类方法,需要传入datetime对象作为参数;但month是datetime对象的属性,不是可调用的方法,你错误地给它加了括号当作方法使用,因此触发类型错误。
修正方案
方案1:修正lambda函数
将datetime.month(...)改为调用datetime对象的.month属性:
df2['Month'] = df2['datetime'].apply(lambda x: datetime.fromtimestamp(x / 1000).month)
方案2:更高效的pandas原生处理
避免使用apply(循环处理效率低),直接用pandas的时间序列工具转换并提取字段:
import pandas as pd # 将毫秒时间戳转为pandas datetime类型 df2['datetime'] = pd.to_datetime(df2['datetime'], unit='ms') # 直接提取星期几(周一为0)和月份 df2['week_day'] = df2['datetime'].dt.weekday df2['Month'] = df2['datetime'].dt.month
内容的提问来源于stack exchange,提问作者J.Billman
相关产品推荐
相关产品推荐

