By using the difference (-)
"2023-08-14 21:56"
(s - s.dt.floor('D') - specific_time)
-> converts into:
0 1 days 18:56:00
1 1 days 20:04:00
2 1 days 12:43:00
3 1 days 09:05:00
4 1 days 19:19:00
and this: .dt.total_seconds() / 3600
transform into hours.
import pandas as pd
data = [
"2023-08-14 21:56",
"2023-08-15 23:04",
"2023-08-16 15:43",
"2023-08-17 12:05",
"2023-08-18 22:19",
]
# Convert the list of strings to a datetime Series
s = pd.Series(data, dtype="datetime64[ns]")
# Define the specific time as a timedelta
specific_time = pd.to_timedelta("21:00:00")
# Calculate the time difference in hours for each datetime
time_differences = (s - s.dt.floor('D') + specific_time).dt.total_seconds() / 3600
print(time_differences)
output:
0 0.933333
1 2.066667
2 -5.283333
3 0.083333
4 1.316667
dtype: float64
function:
def calculate_time_differences(data, specific_time):
# Convert the list of strings to a datetime Series
s = pd.Series(data, dtype="datetime64[ns]")
# Calculate the time difference in hours for each datetime
time_differences = (s - s.dt.floor('D') - specific_time).dt.total_seconds() / 3600
return time_differences