I was recently writing a project in PyCharm that downloaded large video files. I wanted to have a typical progress meter as the download progressed.
I asked this question to the AI Assistant "calculate time left based on start time, current time, total size and current size".
This is the response that it generated.
To calculate the time left for a download based on the start time, current time, total size, and the current size of the file downloaded, you can use the following approach:
Use the Formula
-
Determine the elapsed time:
- Elapsed time can be calculated by subtracting the
start_time
from the current_time
.
-
Calculate the download speed:
- Download speed is
current_size / elapsed_time
.
-
Calculate the remaining size:
- Remaining size is
total_size - current_size
.
-
Estimate the time left:
- Time left is
remaining_size / download_speed
.
Here is a Python code snippet implementing this logic:
import time
def calculate_time_left(start_time, current_time, total_size, current_size):
# Elapsed time in seconds
elapsed_time = current_time - start_time
# Avoid division by zero
if elapsed_time == 0:
return "Calculating..."
# Download speed in size per second
download_speed = current_size / elapsed_time
# Remaining size
remaining_size = total_size - current_size
# Estimate time left in seconds
if download_speed > 0:
time_left = remaining_size / download_speed
else:
return "Speed is too slow to calculate time left"
# Return time left in a human-readable format
minutes, seconds = divmod(time_left, 60)
return f"{int(minutes)} minutes {int(seconds)} seconds left"