Dave Will
Dave Will

Reputation: 95

Converting integers into time format

I have the following data frame:

data = {"hours": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]}
df = pd.DataFrame(data)

I have been trying to get the following format of time:

1:00:00, 2:00:00 ... 12:00:00 etc

so that at the end when typing df.dtypes I get the follwoing format as well: datetime64[ns] but unfortunately I was not successful. I have tried the following:

df['new_hours'] = pd.to_datetime(df['hours'])

but it did not work.

Upvotes: 0

Views: 39

Answers (1)

JarroVGIT
JarroVGIT

Reputation: 5279

This works:

import pandas as pd

data = {"hours": [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]}
df = pd.DataFrame(data)

df['hours'] = (pd.Timestamp('now').normalize() + (pd.to_timedelta(df['hours'], unit='h'))).dt.time

print(df.head())
#       hours
# 0  01:00:00
# 1  02:00:00
# 2  03:00:00
# 3  04:00:00
# 4  05:00:00

Explanation:

  • df['hours'] = overwrites the Series named 'hours'

  • (pd.Timestamp('now').normalize() creates a datetime'now' and normalize() makes it a midnight datetime (e.g. today 00:00:00)

  • + (pd.to_timedelta(df['hours'],unit='h')) creates a Timedelta object based on the integer in the 'hours' Series, unit parameter ensures its interpreted as hour. Adds this to the previous midnight datetime.

  • ).dt.time takes the time of the datetime that was constructed in the previous 2 bull-its.

Upvotes: 1

Related Questions