0

i have a csv file like this:

"time","student","items"

"09:00:00","Tim","apple"

"09:00:05","Jason","orange"

"09:00:10","Emily","grape"

"09:00:15","Ivy","kiwi"

(many time and the interval is 5 second)

i want to use pandas to let time to become the index and i want the time looks like the following 2019-05-09 09:00:00

datetime.datetime(2019, 5, 9, 9, 0)

i can only get the simple one

time

09:00:00

09:00:05

09:00:10

09:00:15

and can't get the type mentioned above

import pandas as pd 

df0509 = pd.read_csv("0509.csv",index_col="time")
Chris
  • 15,819
  • 3
  • 24
  • 37
9898
  • 3
  • 3
  • You'll need to specify the format of the datetime object you want. You can read up on it here: https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior – Chris May 20 '19 at 14:19
  • i know i can use .apply(lambda x: datetime.strptime('2019-05-09 {}'.format(x), '%Y-%m-%d %H:%M:%S')) for time if it is at the first column. However, it cannot apply for index – 9898 May 20 '19 at 14:30
  • Possible duplicate of [Convert DataFrame column type from string to datetime](https://stackoverflow.com/questions/17134716/convert-dataframe-column-type-from-string-to-datetime) – skillsmuggler May 20 '19 at 14:36

1 Answers1

0

Make use of pd.to_datetime()

Code

import pandas as pd

# Read data
data = pd.read_csv("0509.csv")

# Converting to datetime
data['time'] = pd.to_datetime(data['time'])

# Display dataframe
data.head()

Output

                 time student   items
0 2019-05-20 09:00:00     Tim   apple
1 2019-05-20 09:00:05   Jason  orange
2 2019-05-20 09:00:10   Emily   grape
3 2019-05-20 09:00:15     Ivy    kiwi

Setting the date as index

Doing this is not something I would recommend as the index needs to be unique. There's a great chance that multiple rows can have the same date-time.

# Code
data.set_index('time', inplace=True)

# Output
                    student   items
time                               
2019-05-20 09:00:00     Tim   apple
2019-05-20 09:00:05   Jason  orange
2019-05-20 09:00:10   Emily   grape
2019-05-20 09:00:15     Ivy    kiwi

Reference

skillsmuggler
  • 1,862
  • 1
  • 11
  • 16