How can I correctly import strptime in order to calculate the difference between 2 given times in python

Question:

import datetime
a = int(input("sekund1"))
b = int(input("sekund2"))
time1 = datetime.strptime(a,"%H%M") 
time2 = datetime.strptime(b,"%H%M") 
diff = time1 -time2
diff.total_seconds()/3600

I am trying to create a "calculator" for given times in python, my knowledge in the language is very limited and this is how far I’ve managed to come.

Although this is very limited as it will only subtract given seconds, I am trying to subtract 2 given times in the format HH:MM:SS, but this is where I come at a stop.

I get an error

module ‘datetime’ has no attribute ‘strptime’

Asked By: im very stupid

||

Answers:

I tried out your code and found a few tweaks that needed to be made. Following is a code snippet with those tweaks.

from datetime import datetime     # To make "datetime.strptime()" work
a = str(input("sekund1 "))
b = str(input("sekund2 "))
time1 = datetime.strptime(a,"%H:%M")    # Was missing the ":" symbol
time2 = datetime.strptime(b,"%H:%M")    # Was missing the ":" symbol
diff = time1 -time2

print("Difference in hours:", diff.total_seconds()/3600)

Here was a sample of output.

@Una:~/Python_Programs/Seconds$ python3 Diff.py 
sekund1 12:45
sekund2 10:45
Difference in hours: 2.0

Give that a try.

Answered By: NoDakker

I am not sure I understand what you want to do but here my interpretation of it, in the simplest way I could think of.

import datetime

a = input("a [HH:MM:SS] : ")
b = input("b [HH:MM:SS] : ")

a_from_str_to_list = a.split(':')
b_from_str_to_list = b.split(':')

a_seconds = ( int(a_from_str_to_list[0]) * 3600 ) + ( int(a_from_str_to_list[1]) * 60 ) + int(a_from_str_to_list[2])

b_seconds = ( int(b_from_str_to_list[0]) * 3600 ) + ( int(b_from_str_to_list[1]) * 60 ) + int(b_from_str_to_list[2])

c_secondds = a_seconds - b_seconds

t = str(datetime.timedelta(seconds = c_secondds))

print(t)

given 01:01:13 and 00:00:13 as input it would print 01:01:00

Answered By: Sami Rachdi
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.