Sangjun
Sangjun

Reputation: 21

I want to change timestamp to datetime in dataframe

I want to change timestamp to datetime in dataframe. But it shows TypeError : string indices must be integers How can I solve it?

I'm using Python version 3.x

import pandas as pd
df = pd.DataFrame(contents)
df.columns = ['date', 'open', 'high', 'low', 'close', 'volume']
df['date'] = [datetime.datetime.strptime(x['date'], "%Y-%m-%dT%H:%M:%S") for x in df]
print(df)

I expect the output 2019-05-14 08:56:07, but the actual output is the error message 'TypeError: string indices must be integers'

Upvotes: 1

Views: 158

Answers (2)

Sangjun
Sangjun

Reputation: 21

I solved by other way using dataframe.apply()

def time_date(thetime):
    return datetime.datetime.fromtimestamp(thetime/1000).strftime('%Y-%m-%d %H:%M:%S')

df['date2'] = df['date'].apply(time_date)


              date       open  ...       volume                date2
1896  1559746800000  9441000.0  ...  3585.904319  2019-06-06 00:00:00
1897  1559833200000  9300000.0  ...  4411.323529  2019-06-07 00:00:00
1898  1559919600000  9639000.0  ...  2459.404861  2019-06-08 00:00:00
1899  1560006000000  9692000.0  ...  1855.680572  2019-06-09 00:00:00
1900  1560092400000  9577000.0  ...  4817.845051  2019-06-10 00:00:00

Thanks

Upvotes: 1

Cornel
Cornel

Reputation: 72

Hi you can give this a go:

from datetime import datetime

df['date']= [datetime.fromtimestamp(x['date']) for x in df['date']]

print(df['date'])

EDIT:

It can also be your for x in df this does not return a row -> this returns a column name.

Upvotes: 0

Related Questions