简体   繁体   中英

Pandas: Derive a days, hours, minutes, seconds timestamp from available data

With this expected data, I am trying to see if I can return the following result:

#expected result
'12.22:05:38.3911208'
# mwe
df = pd.DataFrame({
                   'wrong_ts': '1970-01-13T22:05:38.391+0000',
                   'minutes': 18605,
                   'seconds': 38,
                   'ms': 391,
                   'expected': '12.22:05:38.3911208'})

This gets me fairly close, but not quite:

df['duration'] = df['minutes'].astype(str) + 'm ' + df['seconds'].astype(str) + 's ' +  df['ms'].astype(str) + 'ms'

pd.to_timedelta(df.duration)
# 12 days 22:05:38.391000

You could try this. Using to_pytimedelta and converting the time to string. Then from the resulting string, split and get the days and time in the required format.

time_delta = pd.to_timedelta(df.duration)

my_date = time_delta.dt.to_pytimedelta().astype(str)
split_time = my_date[0].split(',')
days = split_time[0]
time = split_time[1].strip()
print(days.split('days')[0].strip() + '.' + time)

Output:

12.22:05:38.391000

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM