Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Data Science by (17.6k points)

I've read loads of SO answers but can't find a clear solution.

I have this data in a df called day1 which represents hours:

1    10:53

2    12:17

3    14:46

4    16:36

5    18:39

6    20:31

7    22:28

Name: time, dtype: object>

I want to convert it into a time format. But when I do this:

day1.time = pd.to_datetime(day1.time, format='H%:M%')

The result includes today's date:

1   2015-09-03 10:53:00

2   2015-09-03 12:17:00

3   2015-09-03 14:46:00

4   2015-09-03 16:36:00

5   2015-09-03 18:39:00

6   2015-09-03 20:31:00

7   2015-09-03 22:28:00

Name: time, dtype: datetime64[ns]>

It seems the format argument isn't working - how do I get the time as shown here without the date?

Update

The following formats the time correctly, but somehow the column is still an object type. Why doesn't it convert to datetime64?

day1['time'] = pd.to_datetime(day1['time'], format='%H:%M').dt.time

1    10:53:00

2    12:17:00

3    14:46:00

4    16:36:00

5    18:39:00

6    20:31:00

7    22:28:00

Name: time, dtype: object>

1 Answer

0 votes
by (41.4k points)

After performing the conversion you can use the datetime accessor dt to access just the hour or time component:

In [51]:

df['hour'] = pd.to_datetime(df['time'], format='%H:%M').dt.hour

df

Out[51]:

        time  hour

index             

1      10:53    10

2      12:17    12

3      14:46    14

4      16:36    16

5      18:39    18

6      20:31    20

7      22:28    22

Also your format string H%:M% is malformed, it's likely to raise a ValueError: ':' is a bad directive in format 'H%:M%'

Regarding your last comment the dtype is datetime.time not datetime:

In [53]:

df['time'].iloc[0]

Out[53]:

datetime.time(10, 53)

If you wish to learn more about Pandas visit this Pandas Tutorial.

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...