Here I am using Pandas to convert excel time string to Panda data time data. Here the time string is recorded in the format as 'day.hour:minite:seconds' The day is recorded as absolute number of days.
What should I do in this case?
I attached the sample raw code here.
import pandas as pd
data = {'Raw_time_string':['00:00:00','00:00:01','23:59:59','1.00:00:01','357.23:59:59']}
df = pd.DataFrame(data=data)
df['Time_object'] = pd.to_datetime(df['Raw_time_string'], format='[%d.%H:%M%S]')
CodePudding user response:
Here I have worked out a few lines of handy code but should be workable. Hope there are more elegant solutions.
def StringtoSec(string):
# Convert time string to seconds
# "45.15:16:49" = 45 days 15 hours 16 mins 49 sec
if '.' in string:
day_seg = string.split('.')
days = int(day_seg[0])
time_seg = day_seg[1].split(':')
hours = int(time_seg[0])
mins = int(time_seg[1])
secs = int(time_seg[2])
total_sec = ((days*24 hours)*60 mins)*60 secs
return total_sec
else:
time_seg = string.split(':')
hours = int(time_seg[0])
mins = int(time_seg[1])
secs = int(time_seg[2])
total_sec = ((hours)*60 mins)*60 secs
return total_sec
df_detail['Total_Time(s)'] = df_detail['Raw_time_string'].apply(lambda x : StringtoSec(x))
CodePudding user response:
Assuming you are using the datetime python library to convert from string to a datetime object you cannot use "%d" for absolute dates. "%d" is used for the day of the month from 01 to 31
You can however use "%j" which denotes the day number of year from 001 to 366
See here for examples