I have a column with times that are not timestamps and would like to know the timedelta to 00:30:00 o'clock. However, I can only find methods for timestamps.
df['Time'] = ['22:30:00', '23:30:00', '00:15:00']
The intended result should look something like this:
df['Output'] = ['02:00:00', '01:00:00', '00:15:00']
This code convert a type of Time value from str
to datetime
(date
is automatically set as 1900-01-01). Then, calculated timedelta
by setting standardTime as 1900-01-02-00:30:00.
import pandas as pd
from datetime import datetime, timedelta
df = pd.DataFrame()
df['Time'] = ['22:30:00', '23:30:00', '00:15:00']
standardTime = datetime(1900, 1, 2, 0, 30, 0)
df['Time'] = pd.to_datetime(df['Time'], format='%H:%M:%S')
df['Output'] = df['Time'].apply(lambda x: standardTime-x).astype(str).str[7:] # without astype(str).str[7:], the Output value include a day such as "0 days 01:00:00"
print(df)
# Time Output
#0 1900-01-01 22:30:00 02:00:00
#1 1900-01-01 23:30:00 01:00:00
#2 1900-01-01 00:15:00 00:15:00