format hours in pd.to_datetime in python

In Pandas, pd.to_datetime() function can be used to convert a column to datetime. It can parse a wide variety of date formats including format codes representing hours.

To parse hours, you can use %H format code, which represents 24 hour format (00–23). Here's an example:

main.py
import pandas as pd

# create example dataframe
df = pd.DataFrame({'Time':['00:00', '12:34', '23:59']})

# convert Time column to datetime
df['Time'] = pd.to_datetime(df['Time'], format='%H:%M')

print(df)
206 chars
10 lines

Output:

main.py
                 Time
0 1900-01-01 00:00:00
1 1900-01-01 12:34:00
2 1900-01-01 23:59:00
88 chars
5 lines

In this example, we converted the Time column which has format hh:mm to a datetime column by specifying the format as %H:%M.

related categories

gistlibby LogSnag