-2

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'
Bonifacio2
  • 3,405
  • 6
  • 34
  • 54
Brain_overflowed
  • 426
  • 1
  • 5
  • 21

2 Answers2

1

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
BENY
  • 317,841
  • 20
  • 164
  • 234
0

df.TimeStamp = pd.to_datetime(df_sr4500.TimeStamp) is sufficient.

To get the hour or the minute from this column you need the following:

[i.hour for i in df.TimeStamp]

Note: .dt access an individual item but you are trying to access it using an entire series.

A.Kot
  • 7,615
  • 2
  • 22
  • 24