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']
CodePudding user response:
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
CodePudding user response:
One could want to use datetime.time
as data structures, but these cannot be subtracted, so you can't conveniently get a timedelta
from them.
On the other hand, datetime.datetime
objects can be subtracted, so if you're always interested in positive deltas, you could construct a datetime
object from your time representation using 1970-01-01
as date, and compare that to 1970-01-02T00:30
.
For instance, if your times are stored as strings (as per your snippet):
import datetime as dt
def timedelta_to_0_30(time_string: str) -> dt.timedelta:
time_string_as_datetime = dt.datetime.fromisoformat(f"1970-01-01T{time_string}")
return dt.datetime(1970, 1, 2, 0, 30) - time_string_as_datetime
my_time_string = "22:30:00"
timedelta_to_0_30(my_time_string) # 2:00:00