How can I create a code that charges a 'penny' for every second that my code is ran? (Python)

Question:

I want to create a code that charges ‘money’ for every second that my program is ran. For example, if I am charging 1 cent for every second that the program is ran, and the program is ran for 10 seconds, I want a statement to be printed like "You have ran the program for 10 seconds, and will be charged 10 cents" at the end of my program.

I don’t even know where to start on this, but so far, I’ve created a code that shows me how long my program has been ran for. The code looks like this:

from datetime import datetime
start_time = datetime.now()
#my code
end_time = datetime.now()
print("Duration:", end_time-start_time)

How can I go from here?

Asked By: venusss

||

Answers:

You’re mostly there; just get the total_seconds() from the timedelta you got from subtracting the two datetimes.

elapsed = (end_time-start_time).total_seconds()
print(f"You have ran the program for {elapsed} seconds, and will be charged {elapsed} cents.")
Answered By: Samwise
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.