Danny Diaz
Danny Diaz

Reputation: 375

How to format pandas datetime64 type to show only the time and not the date and time

I am trying to change a column type from object to a datetime64 but want it to display only the time as hours:minute.

The column is a string formatted 13:45:00. When I change the data type to datetime64 it now prints it with a made up date (1900-01-01 13:45:00).

I want the column data type to be a datetime64 type (so I can do comparisons and operations later) but only I want it display the time in hour:minute format without the seconds and without the date. Example - 13:45

Everything I can find in google is about getting only the date to show and maintain the datetime64 datatype, which I was able to do.

I have tried messing with the pd.to_datetime().dt.strftime('%H:%M'). It correctly formats the column but its datatype is object not datetime64.

cycle_trips_df['Checkout Date'] = pd.to_datetime(
    cycle_trips_df['Checkout Date'], infer_datetime_format=True
    ).dt.normalize() #strftime('%m/%d/%Y') # format='%m/%d/%Y').dt.date

cycle_trips_df['Checkout Time'] = pd.to_datetime(
    cycle_trips_df['Checkout Time'], format='%H:%M:%S'
).dt.strftime('%H:%M')
print(cycle_trips_df.dtypes)

[Output]

Checkout Date datetime64[ns]
Checkout Time object

Upvotes: 2

Views: 6344

Answers (3)

c0nn3ct
c0nn3ct

Reputation: 1

May use some like:

df['time'] = df['time'].apply(lambda x: datetime.strptime(x, "%H:%M:%S").time())

It will be object

Upvotes: 0

Robert Altena
Robert Altena

Reputation: 795

Distinguish between the data and your views of that data. A datetime64 is a datetime64 and will be printed by default as a full date string. You can use strftime to get the time part.

str = "13:45:00"                     # Your string.
dt64 = pd.to_datetime(str)           # the datetime64 object
timestr = dt64.strftime("%H:%M:%S")  # extracting the time string from the datetime64.

Upvotes: 1

Andy Hayden
Andy Hayden

Reputation: 375855

Use a timedelta rather than a datetime:

In [11]: s = pd.Series(['13:45:00'])

In [12]: pd.to_timedelta(s)
Out[12]:
0   13:45:00
dtype: timedelta64[ns]

Upvotes: 2

Related Questions