Suraj Bhatia
Suraj Bhatia

Reputation: 1333

String to time python in hours and minutes and calculate difference

I am taking time as input from the user in the HH:MM format. Let's say 00:00 and now I want to keep adding a minute to the time and make it 00:01, 00:02 and so on.

Also, I am taking two inputs form the user start_time and end_time as strings. How can I calculate the difference between the two times as well in minutes?

I am new to Python and any help would be appreciated!

I am using the below code:

#to calculate difference in time
time_diff = datetime.strptime(end_time, '%H:%M') - datetime.strptime(start_time, '%H:%M')
minutes = int(time_diff.total_seconds()/60)
print minutes

#to convert string to time format HH:MM
start_time = datetime.strptime(start_time, '%H:%M').time()

#to increment time by 1 minute
start_time = start_time + datetime.timedelta(minutes=1)

I am not able to increment the start_time using timedelta.

Upvotes: 2

Views: 15637

Answers (2)

msmi235
msmi235

Reputation: 1

First part of your question, you can use the datetime module:

from datetime import datetime as dt
from datetime import timedelta as td
UsrInput = '00:00'
fmtString = '%H:%M'
myTime = dt.strptime(UsrInput, fmtString)
increment = td(0,1)
for count in range(10):
    myTime += increment
    print (dt.strftime(myTime, fmtString))

Second part will also use datetime, as such:

from datetime import datetime as dt
from datetime import timedelta as td
start_time = '00:01'
end_time = '00:23'
fmtString = '%H:%M'
myStart = dt.strptime(start_time, fmtString)
myEnd = dt.strptime(end_time, fmtString)
difference = myEnd - myStart
print(td.strftime(difference, '%M')

Upvotes: 0

James
James

Reputation: 2731

import datetime

time_diff = datetime.datetime.strptime(end_time, '%H:%M') - datetime.datetime.strptime(start_time, '%H:%M')
minutes = int(time_diff.total_seconds()/60)
print minutes

datetime is a class of the datetime module that has a classmethod called strptime. The nomenclature is a bit confusing, but this should work as you intend it to.

As for adding a time delta, you'll need store the start time as a datetime object in order to get that to work:

start_datetime = datetime.datetime.strptime(start_time, '%H:%M')
start_datetime = start_datetime + datetime.timedelta(minutes=1)
print start_datetime

Upvotes: 1

Related Questions