1

I'm new to python 3 I have to get a datetime value from a .csv file and split into a separate date and time value column.

csv file:

C1,C2,V2,Time_Stamp
0.1,1.3,-0.9,13/6/2017 14:42
0.1,1.2,-0.9,13/6/2017 14:42
0.1,1.3,-0.9,13/6/2017 14:42
0.1,1.3,-0.9,13/6/2017 14:42

Initially, what I have is this under Time_Stamp:

Output after running:

timestamps = Data.Time_Stamp
for i in timestamps:
    dataobj = dt.datetime.strptime(i, "%d/%m/%Y %H:%M") #Time_Stamp datetime format - need set varibale to print
    print (dataobj) #Prints the following output

Output:

13/6/2017 14:42

13/6/2017 14:42

13/6/2017 14:42

13/6/2017 14:42

13/6/2017 14:42

Based on the above output, it has date and time together in a column, I want the date to be in a different column and the time to be in another.

   13/6/2017 14:42    13/6/2017   14:42

   13/6/2017 14:42    13/6/2017   14:42

   13/6/2017 14:42    13/6/2017   14:42

   13/6/2017 14:42    13/6/2017   14:42

   13/6/2017 14:42    13/6/2017   14:42

I tried following examples from this Splitting timestamp column into seperate date and time columns but i could not get similar outputs.

import pandas as pd
import csv 
import datetime as dt

print (row)

Data = pd.DataFrame.from_csv('csv_date.csv')
print (Data)

timestamps = Data.Time_Stamp
for i in timestamps:
    dataobj = datetime.strptime(i, "%d/%m/%Y %H:%M")

df['new_date'] = [i.date() for i in Data['Time_Stamp']]
df['new_time'] = [i.time() for i in Data['Time_Stamp']]

Error I faced:

AttributeError                            Traceback (most recent call last)
<ipython-input-137-ca9ed5c25ff2> in <module>()
----> 1 df['new_date'] = [i.date() for i in Data['Time_Stamp']]
      2 df['new_time'] = [i.time() for i in Data['Time_Stamp']]

<ipython-input-137-ca9ed5c25ff2> in <listcomp>(.0)
----> 1 df['new_date'] = [i.date() for i in Data['Time_Stamp']]
      2 df['new_time'] = [i.time() for i in Data['Time_Stamp']]

AttributeError: 'str' object has no attribute 'date'
Sancta Ignis
  • 83
  • 1
  • 10

2 Answers2

2

When reading, use pd.read_csv with parse_dates and infer_datetime_format as True.

Data = pd.read_csv('csv_date.csv', parse_dates=['Time_Stamp'], infer_datetime_format=True)

Next, you can just extract the date & time:

Data['Date'] = Data.Time_Stamp.dt.date
Data['Time'] = Data.Time_Stamp.dt.time
cs95
  • 379,657
  • 97
  • 704
  • 746
0
Data = pd.DataFrame.from_csv('csv_date.csv')
Data['new_times'] = Data['Time_Stamp'].apply(lambda x:datetime.strptime(x, "%d/%m/%Y %H:%M"))

use apply and lambda deal with Dataframe

Vity Lin
  • 499
  • 2
  • 5
  • 11