0

Why I get the error in the below code:

there is a column and I want to implement Timestamp on it:

df['date']


0       2014-09-04 00:00:00
1       2014-09-12 00:00:00
2       2014-09-04 00:00:00
3       2014-09-05 00:00:00
4       2014-09-06 00:00:00
               ...         
1049    2015-09-16 00:00:00
1050    2015-10-13 00:00:00
1051    2015-10-13 00:00:00
1052    2015-10-22 00:00:00
1053    2015-10-20 00:00:00
Name: date, Length: 1054, dtype: object

df['date']=df['date'].agg(pd.Timestamp)

Here is the given error:

TypeError: Cannot convert input
 [0       2014-09-04 00:00:00
1       2014-09-12 00:00:00
2       2014-09-04 00:00:00
3       2014-09-05 00:00:00
4       2014-09-06 00:00:00
               ...         
1049    2015-09-16 00:00:00
1050    2015-10-13 00:00:00
1051    2015-10-13 00:00:00
1052    2015-10-22 00:00:00
1053    2015-10-20 00:00:00
Name: date, Length: 1054, dtype: object] of type <class 'pandas.core.series.Series'> to Timestamp
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
hamideh
  • 75
  • 5

1 Answers1

1

First convert df['date'] to datetime, type of element in column is str.

df['date'] = pd.to_datetime(df['date'])
I'mahdi
  • 23,382
  • 5
  • 22
  • 30
  • I run this code as well but i got error again, ```ValueError: day is out of range for month``` – hamideh Jul 19 '22 at 07:33
  • @hamideh, try this : `pd.to_datetime(df['date'], format='%Y-%d-%m %H:%M:%S')` – I'mahdi Jul 19 '22 at 07:38
  • 1
    @hamideh, You can use also : `pd.to_datetime(df['date'], format='%Y-%d-%m %H:%M:%S',errors='ignore')`, this code ignore errors. – I'mahdi Jul 19 '22 at 07:40
  • great! that works !! now can I calculate the difference between this field and today? – hamideh Jul 19 '22 at 07:50
  • @hamideh, this is another question, this better ask a new question, Are you wanting this : `pd.Timestamp.now().normalize() - df['date']` – I'mahdi Jul 19 '22 at 08:02
  • yes I used your function and the last problem: ```df['Diff']=df['date'].agg(lambda x:pd.Timestamp.now().normalize()-x)``` TypeError: unsupported operand type(s) for -: 'Timestamp' and 'str' – hamideh Jul 19 '22 at 08:32
  • @hamideh, before using your code add this line : `df['date'] = pd.to_datetime(df['date'])` – I'mahdi Jul 19 '22 at 08:33
  • you mean this: ```df['date']=pd.to_datetime(df['date'], format='%Y-%d-%m %H:%M:%S',errors='ignore')''' then this? ```df['Diff']=df['date'].agg(lambda x:pd.Timestamp.now().normalize()-x)''' – hamideh Jul 19 '22 at 08:44
  • @hamideh, yes... – I'mahdi Jul 19 '22 at 08:45
  • thats what i did. it doesn`t work ```TypeError: unsupported operand type(s) for -: 'Timestamp' and 'str``` – hamideh Jul 19 '22 at 08:49
  • @hamideh, i check, you dont' get any errors, this error because type of column `str` but if convert to datetime, you should not get any error. – I'mahdi Jul 19 '22 at 09:00
  • 1
    I understand. this error is weird! I tried it several times. – hamideh Jul 19 '22 at 09:14