Diop Chopra
Diop Chopra

Reputation: 319

Convert timestamp object to datetime

data = [07222020051111, 07222020051058, 07222020051107]

df = pd.DataFrame(data, columns = ['time'])

I am seeking to transform the data in the 'time' column to display as follows:

   time
0 2020-07-22 05:11:11
1 2020-07-22 05:10:58
2 2020-07-22 05:11:07

I have tried:

df['time'] = df['time'].dt.strptime('%m-%d-%Y %H:%m:%s')

df['time'] = pd.to_numeric(df['time'])

both without success.

I am very new to this so please excuse if this seems very basic.

Upvotes: 0

Views: 1978

Answers (2)

Zellint
Zellint

Reputation: 109

use to_datetime function to convert a column to datetime type:

df['timestamp'] = pd.to_datetime(df['time'], format='%m%d%Y%H%M%S')

here's the format arg is your data's date format, and not your desired output format

Upvotes: 1

Martyn Ward
Martyn Ward

Reputation: 36

If you use the datetime module to parse the strings into dates first then creating the dataframe using datetimes for data takes care of it.

    data = ["07222020051111", "07222020051058", "07222020051107"]
    data2 = [datetime.datetime.strptime(i,"%m%d%Y%H%M%S") for i in data]
    df = pd.DataFrame(data2, columns = ['time'])

should do it

Upvotes: 0

Related Questions