Brain_overflowed Brain_overflowed - 3 years ago 176
Python Question

Conversion of Strings to Datetime Pandas - tried everything

I know there are a lot of similar questions but I am pretty sure I have tried everything I found

Data:

TimeStamp
10:34:30
10:35:30
10:36:30
10:37:30


I have two different .csv files and I am trying to compare the times from the two in order determine further action.

I want to use
.dt.hour
or
.dt.min
to compare the times. Here's what I tried:
The type always remains str or float and the
.dt.hour
or .
dt.min
does not work

def csv_to_df(path, filename):
dateparse = lambda x: pd.datetime.strptime(x, '%H:%M:%S')
df = pd.read_csv(path + filename, skipinitialspace = True, parse_dates = True, date_parser = dateparse)
return df


I also tried using pd.to_datetime later for conversion. That didn't work either.

df_sr4500.TimeStamp=pd.to_datetime(df_sr4500.TimeStamp).dt.time
print(df_sr4500.TimeStamp[1].dt.hour)

ERROR: AttributeError: 'datetime.time' object has no attribute 'dt'

Wen Wen
Answer Source

IIUC

df.TimeStamp=pd.to_datetime(df.TimeStamp).dt.time

df.TimeStamp[1]
Out[115]: datetime.time(10, 35, 30)

df.TimeStamp[1].hour

Out[119]: 10

In case you need convert new column hour

df.TimeStamp.apply(lambda x : x.hour)
Out[122]: 
0    10
1    10
2    10
3    10
Name: TimeStamp, dtype: int64
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download