I have a time 00:11:21.600000 like this in each row of excel I want to convert to time stamp in hrs and mins
Asked
Active
Viewed 130 times
0
-
I have a column df['time] and wanto convert to time – om9595 Mar 24 '21 at 11:48
-
doesn't it your answer?https://stackoverflow.com/questions/25754405/how-to-extract-hours-and-minutes-from-a-datetime-datetime-object – Vova Mar 24 '21 at 11:57
2 Answers
0
You can use the inbuilt datetime module:
from datetime import datetime
your_time = datetime.strptime('00:11:21.600000', '%H:%M:%S.%f')
Then you have a datetime object your_time
on which you can perform different actions, for example:
Get str with hours and minutes: your_time.strftime('%H:%M')
For more methods see the docs here.

Julian Fock
- 98
- 10
-
df['newcolname'] = datetime.strptime(df['time'], '%H:%M:%S.%f') getting below error – om9595 Mar 24 '21 at 12:08
-
-
it is because you are trying to apply that strptime to whole column, you have to iterate over each item and convert it to datetime object like Julian suggested. – Bijay Regmi Mar 24 '21 at 12:08
-
Could you guide me on how to iterate over each item? I am learning Thank you! – om9595 Mar 24 '21 at 12:10
-
df['newcolname'] = pd.to_datetimee(df['time'], '%H:%M:%S:%f') getting below errorValueError: time data '00:45:36' does not match format '%H:%M:%S:%f' (match) – om9595 Mar 24 '21 at 12:18
-
Two things: 1.: You use `':%f'` instead of `'.%f'` 2.: I was assuming your time formats were uniform '00:11:21.600000 like this', if you have different formats like '00:45:36' you would need to make them uniform or handle edge cases. E.g.: `datetime.strptime(time_str, '%H:%M:%S.%f') if '.' in time_str else datetime.strptime(time_str, '%H:%M:%S')` – Julian Fock Mar 24 '21 at 13:01
0
Adding onto Juilian Focks answer, if you have a column named df["time"]
, you can convert each element into timestamp object by iterating over it as :
from datetime import datetime
for i in range(0,len(df["time"])):
df["time"][i] = df["time"][i].strftime("%H:%M")
or you could use list comprehension as :
dt_array = [x.strftime("%H:%M") for x in df["time"]]
then dt_array
contains whole column as datetime object

Bijay Regmi
- 1,187
- 2
- 11
- 25
-
still getting this error TypeError: strptime() argument 1 must be str, not datetime.time – om9595 Mar 24 '21 at 12:46
-
that means you are trying to convert something into datetime which is already datetime. `df["time"]` is already datetime. – Bijay Regmi Mar 24 '21 at 12:48
-
-
-
-
okay then I have 2 columns df['time] which is start time and df['end'] which is end time and now want to find time difference – om9595 Mar 24 '21 at 13:06
-
you can just do end_time - start_time if both are datetime object. But you might need to create a new question and accept my answer as answer if it worked for you. – Bijay Regmi Mar 24 '21 at 13:09