Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert time (HH:MM:SS) to minutes in python

How to convert HH:MM:SS to Minutes?

I tried below works fine:

  import datetime as DT
  t1 = DT.datetime.strptime('0:10:00', '%H:%M:%S')

I tried another example and getting error:

  import datetime as DT
  t1 = DT.datetime.strptime('9715:56:46', '%H:%M:%S')

Error:

  ValueError: time data '9715:56:46' does not match format '%H:%M:%S'

In this example it support Max 23 for %H, If my hours has more than 23(in this case i have 9715 hours) how to get it?

like image 452
preethy tulpi Avatar asked Jan 25 '18 16:01

preethy tulpi


People also ask

How do you convert HH mm SS to minutes?

Tips: To convert hh:mm:ss time format to minutes: =((HOUR(A2)*60)+MINUTE(A2)+(SECOND(A2)/60)); To convert hh:mm:ss time format to seconds: =HOUR(A2)*3600 + MINUTE(A2)*60 + SECOND(A2).


2 Answers

You can use sum with a generator expression or map:

from operator import mul

my_time = '9715:56:46'
factors = (60, 1, 1/60)

t1 = sum(i*j for i, j in zip(map(int, my_time.split(':')), factors))
t2 = sum(map(mul, map(int, my_time.split(':')), factors))

print(t1)  # 582956.7666666667

assert t1 == t2
like image 80
jpp Avatar answered Sep 30 '22 09:09

jpp


datetime.datetime is a representation of a point in time, not a duration of time.

datetime.timedelta is a representation of a length of time. Observe:

from datetime import timedelta


delta = timedelta(hours=9715, minutes=56, seconds=46)
total_seconds = delta.total_seconds()
minutes = int(total_seconds // 60)
seconds = int(total_seconds % 60)

print('{minutes}:{seconds}'.format(minutes=minutes, seconds=seconds))

EDIT: I changed the code to work with python 2.7.

like image 31
Adam Barnes Avatar answered Sep 30 '22 10:09

Adam Barnes