Converting Datetime to Time in Pandas
Creating Sample Datetime Data
Let’s start by creating a Pandas DataFrame with a Datetime index and column: This DataFrame contains 5 rows with hourly datetime data.
Python
import pandas as pd import numpy as np # Generate a DatetimeIndex with hourly frequency starting from '2023-02-01' dates = pd.date_range( '2023-02-01' , periods = 5 , freq = 'H' ) df = pd.DataFrame() df[ 'Datetime' ] = dates print (df) |
Output:
Datetime
0 2023-02-01 00:00:00
1 2023-02-01 01:00:00
2 2023-02-01 02:00:00
3 2023-02-01 03:00:00
4 2023-02-01 04:00:00
Let’s Extract Time from Datetime using following ways:
1. Using dt.time
Pandas provides the dt.time attribute to extract time from a DatetimeIndex or Series. This extracts the time component into a new column without losing any information.
Python
df[ 'Time' ] = df[ 'Datetime' ].dt.time print (df) |
Output:
Datetime Time
0 2023-02-01 00:00:00 00:00:00
1 2023-02-01 01:00:00 01:00:00
2 2023-02-01 02:00:00 02:00:00
3 2023-02-01 03:00:00 03:00:00
4 2023-02-01 04:00:00 04:00:00
2. Using DatetimeIndex
We can also extract time from the DatetimeIndex.
Python
df.index = dates df.index = df.index.time print (df) |
Output:
Datetime Time
00:00:00 2023-02-01 00:00:00 00:00:00
01:00:00 2023-02-01 01:00:00 01:00:00
02:00:00 2023-02-01 02:00:00 02:00:00
03:00:00 2023-02-01 03:00:00 03:00:00
04:00:00 2023-02-01 04:00:00 04:00:00
3. Timezone Handling
An important consideration with datetime data is timezones. Pandas stores the timezone information and handles conversion properly when extracting the time component.
Let’s set a timezone to the datetime data
Python
df.index = dates df.index = df.index.tz_localize( 'US/Pacific' ) print (df.index) |
Output:
DatetimeIndex(['2023-02-01 00:00:00-08:00', '2023-02-01 01:00:00-08:00',
'2023-02-01 02:00:00-08:00', '2023-02-01 03:00:00-08:00',
'2023-02-01 04:00:00-08:00'],
dtype='datetime64[ns, US/Pacific]', freq=None)
How to Change Pandas Dataframe Datetime to Time
The DatetimeIndex contains datetime64[ns] data type, which represents timestamps with nanosecond precision. In many cases, we may just want to extract the time component from a Pandas Datetime column or index.
Let’s discuss easy ways to convert the Datetime to Time data while preserving all the time information using pandas