The code:
JavaScript
x
5
1
import pandas as pd
2
import datetime as dt
3
d1 = pd.to_datetime(df.dates, errors='coerce')
4
d1 = pd.to_timedelta(d1).dt.days
5
i have lots of dates in a column which i want to convert to number of days but i simply keep getting errors. im new to pandas so sorry if the question is silly
JavaScript
1
7
1
2014-07-29
2
2008-11-14
3
2010-04-20
4
2011-08-31
5
2002-07-29
6
2013-10-29
7
but why am i getting errors and how to fix them.
JavaScript
1
29
29
1
TypeError Traceback (most recent call last)
2
<ipython-input-119-298bf748984e> in <module>()
3
1 d1 = pd.to_datetime(df.dates, errors='coerce')
4
----> 2 d1 = pd.to_timedelta(d1).dt.days
5
6
2 frames
7
/usr/local/lib/python3.7/dist-packages/pandas/core/tools/timedeltas.py in to_timedelta(arg, unit, errors)
8
122 return arg
9
123 elif isinstance(arg, ABCSeries):
10
--> 124 values = _convert_listlike(arg._values, unit=unit, errors=errors)
11
125 return arg._constructor(values, index=arg.index, name=arg.name)
12
126 elif isinstance(arg, ABCIndex):
13
14
/usr/local/lib/python3.7/dist-packages/pandas/core/tools/timedeltas.py in _convert_listlike(arg, unit, errors, name)
15
171
16
172 try:
17
--> 173 td64arr = sequence_to_td64ns(arg, unit=unit, errors=errors, copy=False)[0]
18
174 except ValueError:
19
175 if errors == "ignore":
20
21
/usr/local/lib/python3.7/dist-packages/pandas/core/arrays/timedeltas.py in sequence_to_td64ns(data, copy, unit, errors)
22
1018 else:
23
1019 # This includes datetime64-dtype, see GH#23539, GH#29794
24
-> 1020 raise TypeError(f"dtype {data.dtype} cannot be converted to timedelta64[ns]")
25
1021
26
1022 data = np.array(data, copy=copy)
27
28
TypeError: dtype datetime64[ns] cannot be converted to timedelta64[ns]
29
Thank you
Advertisement
Answer
To get the number of days to now, use:
JavaScript
1
13
13
1
today = pd.Timestamp.today().normalize()
2
d1 = (today - pd.to_datetime(df['dates'], errors='coerce')).dt.days
3
print(d1)
4
5
# Output
6
0 2910
7
1 4993
8
2 4471
9
3 3973
10
4 7293
11
5 3183
12
Name: dates, dtype: int64
13