Xodarap777
Xodarap777

Reputation: 1376

How to convert time object into total minutes python

I have objects of the form '00:00:00.0000000' from which I simply want to extract a float number of minutes. From import time I so far have this:

>>> reformat = time.strptime('00:05:36.0100000', '%H:%M:%S.%f0')
>>> print reformat
time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=0, tm_min=5, tm_sec=36, tm_wday=0, tm_yday=1, tm_isdst=-1)

It seems like this should follow with something like time.getminutes(reformat) or reformat.minutes() and voila. I can't find such an operation.

Upvotes: 6

Views: 39818

Answers (2)

unlockme
unlockme

Reputation: 4255

if it is a datetime time object i.e. from datetime import time. you can calculate it simply as

timeobject.hour*60+timeobject.minute+timeobject.second/60

Since you want minute resolution, I doubt there is need for second or even microsecond accuracy

Upvotes: 6

unutbu
unutbu

Reputation: 880697

Parse the date string as a datetime.datetime. Since the date string has no year, month or day, the datetime will assume the date to be 1900-1-1. If we subtract datetime.datetime(1900,1,1) we'll obtain a datetime.timedelta object which has a total_seconds method. Conversion to minutes is then easy:

Subtract it from

import datetime as DT
t1 = DT.datetime.strptime('00:05:36.0100000', '%H:%M:%S.%f0')
t2 = DT.datetime(1900,1,1)

print((t1-t2).total_seconds() / 60.0)

yields

5.60016666667

Upvotes: 12

Related Questions