Home > Enterprise >  How to convert timestamp to integer in Pandas dataframe. I tried to_numeric() function but it's
How to convert timestamp to integer in Pandas dataframe. I tried to_numeric() function but it's

Time:09-23

I want to convert a given time say 09:25:59 (hh:mm:ss) into a integer value in pandas. How can i do that. Actually, my requirement is i should know the number of minutes elapsed from mid-night ( 00:00:00 hrs ) of that day. For example, 09:25:59 corresponds to 565 minutes. How can i do that in Python Pandas.

CodePudding user response:

from datetime import timedelta

hh, mm, ss = 9, 25, 59
delta = timedelta(hours=hh, minutes=mm, seconds=ss)
total_seconds = delta.total_seconds()
minutes = int(total_seconds // 60)

minutes has the the minutes elapsed.

CodePudding user response:

I think it will be useful with the use of a dataframe sample:

import pandas as pd
import datetime
data = {"time":["09:25:59", "09:35:59"],
        "minutes_from_midnight": ""}
df = pd.DataFrame(data) # create df
# you don't seem to care about the date, so keep only the time from the datetime dtype
# create a datetime.datetime object to use for timedeltas
df["time"] = pd.to_datetime(df["time"], format="%H:%M:%S") 
df['time'] = [datetime.datetime.time(d) for d in df['time']] # keep only the time
df

enter image description here

You can then do:

# your comparison value
midnight= "00:00:00"
# https://stackoverflow.com/a/48967889/13834173
midnight = datetime.datetime.strptime(midnight, "%H:%M:%S").time() 
# fill the empty column with the timedeltas
from datetime import datetime, date
df["minutes_from_midnight"] = df["time"].apply(lambda
  x: int((datetime.combine(date.today(), x) - datetime.combine(date.today(), midnight))
  .total_seconds()//60))
df

enter image description here

# example with the 1st row time value
target_time = df["time"][0]

# using datetime.combine
delta= datetime.combine(date.today(), target_time) - datetime.combine(date.today(), midnight)
seconds = delta.total_seconds()
minutes = seconds//60
print(int(minutes)) # 565
  • Related