Adam Martin
Adam Martin

Reputation: 23

python hh:mm:ss to seconds on python 3

I am trying to write a program that checks the avg speed of a road. This program will be where you input two times point1-point2. Then the program works out the difference. This all works. The only thing I need is the difference output in HH:MM:SS and I need it in seconds or minutes. This will collect the time to convert from the difference. My code so far is:

from datetime import datetime
#start
print ("Welcome to This Speed Check!")

#varibles
distance=int(input("How far did you travel!(Miles)"))
time1=input("Whats was the time you went past the first point(H:M:S)?")
time2=input("What was the finishing time?")
FMT = '%H:%M:%S'
diffrence = datetime.strptime(time2, FMT) - datetime.strptime(time1, FMT)
print(diffrence)

this all works and gives me what I want I need to convert diffrence to seconds

thanks Adam

Upvotes: 0

Views: 278

Answers (3)

Mike Müller
Mike Müller

Reputation: 85482

This gives you the time difference in seconds:

print(diffrence.total_seconds())

Example:

t1 = datetime.datetime(2005, 1, 1)
t2 = datetime.datetime(2006, 1, 1)
diff = t2 - t1
print(diff.total_seconds())

Output:

31536000.0

Looks alright:

print(365 * 24 * 60 * 60)

31536000

From the docs:

Total seconds in the duration.

Upvotes: 0

amin
amin

Reputation: 1441

Since diffrence is of timedelta type, you should be using datetime.total_seconds() method as:

 print(diffrence.total_seconds())

Upvotes: 1

Cleared
Cleared

Reputation: 2590

You can simply do it by calling seconds:

print(diffrence.seconds)

Upvotes: 0

Related Questions