Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert <m8[ns] to int

I am using pandas and one of the column is of type <m8[ns]. I stored 'days' in it, like 5 days, 3 days, etc.

I want to convert this 'days' column from <m8[ns] to float64, how can I do that?

like image 714
Cheng Avatar asked Oct 28 '25 09:10

Cheng


1 Answers

The dtype you're seeing is the numpy dtype for datetimes, if you just want the days then use dt.day to return you the days:

df['days'] = df['days'].dt.day

See this example:

In [124]:
import datetime as dt
import pandas as pd
df = pd.DataFrame({'dates':pd.date_range(dt.datetime(2016,1,1), periods=10)})
df.info()

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 10 entries, 0 to 9
Data columns (total 1 columns):
dates    10 non-null datetime64[ns]
dtypes: datetime64[ns](1)
memory usage: 160.0 bytes

In [125]:    
df['dates'].dtype

Out[125]:
dtype('<M8[ns]')

In [126]:
df['day'] = df['dates'].dt.day
df

Out[126]:
       dates  day
0 2016-01-01    1
1 2016-01-02    2
2 2016-01-03    3
3 2016-01-04    4
4 2016-01-05    5
5 2016-01-06    6
6 2016-01-07    7
7 2016-01-08    8
8 2016-01-09    9
9 2016-01-10   10

In [127]:    
df.dtypes

Out[127]:
dates    datetime64[ns]
day               int64
dtype: object
like image 165
EdChum Avatar answered Oct 31 '25 05:10

EdChum