3

I've an Excel file having time in mm:ss.0 format. I formatted this into [h]:mm:ss;@ in Excel. How can this be done in Pandas?

Time : 58:44.1 in mm:ss.0 format yields a result 7:58:44 in [h]:mm:ss;@ format in Excel after formatting.

For example:

Input      Desired Output
58:44.1    7:58:44
07:53.3    8:07:53
46:59.6    9:47:00
20:14.0    10:20:14
50:58.7    11:50:59
19:50.0    12:19:50
41:53.5    13:41:53
2
  • So you just want add hour component, increment it and drop the .0 correct? Commented Oct 29, 2015 at 10:27
  • @EdChum - Yes, exactly Commented Oct 29, 2015 at 10:34

1 Answer 1

2

You can slice the string using vectorised str method, then construct datetime using to_datetime from this passing the format string and add a TimedeltaIndex to it and then access the time component using dt.time:

In [199]:
df['Desired Output'] = (pd.to_datetime(df['Input'].str[:-2], format='%M:%S') + pd.TimedeltaIndex(np.arange(7, 7 + len(df)), 'h')).dt.time
df

Out[199]:
     Input Desired Output
0  58:44.1       07:58:44
1  07:53.3       08:07:53
2  46:59.6       09:46:59
3  20:14.0       10:20:14
4  50:58.7       11:50:58
5  19:50.0       12:19:50
6  41:53.5       13:41:53

You can see that the dtype for Desired Output is not datetime.time:

In [201]:
df['Desired Output'].iloc[0]

Out[201]:
datetime.time(7, 58, 44)
Sign up to request clarification or add additional context in comments.

8 Comments

How can I make the Desired Output as datetime.time since I need to find duration of two such input times?
Sorry it is datetime.time as I showed in the last line of code
In my result it is still an object type.
That's correct, you can see though that when you look at a single row values that the dtype is datetime.time
I got two columns namely desiredOutput1 and desiredOutput2 in the format that you've given. I, now, want to calculate the time difference between the two which I'm unable to with an error TypeError: unsupported operand type(s) for -: 'datetime.time' and 'datetime.time'
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.