Home > Mobile >  python datetime not returning month
python datetime not returning month

Time:07-16

I have a dataframe which included a datetime column that is mS from epoch. I have a lamda function that returns that day of week and am trying to get the month as well, but that one is giving me an error,"TypeError: 'getset_descriptor' object is not callable". What am I doing wrong?

code

from datetime import date
from datetime import time
from datetime import datetime
    
    # get the day of week from timestamp where monday = 0
    df2['week_day'] = df2['datetime'].apply(lambda x: datetime.weekday(datetime.fromtimestamp(x / 1000))) #works fine
    print ('converted datetime to weekday')
    df2
    df2['Month'] = df2['datetime'].apply(lambda x: datetime.month(datetime.fromtimestamp(x / 1000)))      # not working fine
    #pd.DatetimeIndex(df2['datetime']).month
    df2

the complete error is

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

CodePudding user response:

.month is a read only class attribute you have to call it without the .() on a date object. so datetime.date.fromtimestamp(x / 1000).month.

CodePudding user response:

datetime.weekday() is a function. datetime.month is an attribute. You should use datetime.fromtimestamp(x/1000).month.

  • Related