Home > Enterprise >  Convert Y-m-d H:M:S format to int in python
Convert Y-m-d H:M:S format to int in python

Time:11-27

Using pandas, I made my csv file into dataframe and named it as data_A

data_A = pd.read_csv("D:/power.csv")

data_A has the column time

time column

I want to convert it to integer type. For example, 2020-01-01 00:00:00 to 20200101000000 The data type of data_A['time'] is object. How can I change the whole column time into int64 values?

CodePudding user response:

The most consistent way (that protects against incidentally odd dates) is to convert the column to datetimes and then to strings:

pd.to_datetime(data_A.time).dt.strftime('%Y%m%d%H%M%S').astype(int)
#0    20200101000000
#1    20200101000020
#Name: time, dtype: int64

But since your time is essentially strings, you can split them by punctuation and then join:

data_A.time.str.split('\W').str.join('').astype(int)
#0    20200101000000
#1    20200101000020
#Name: time, dtype: int64

The second solution is about 40% faster.

  • Related