python-下班倒计时

发布时间 2023-08-18 17:33:48作者: 别打扰我摸鱼

程序使用环境

本程序使用python3编译器

程序效果

image

程序源码

import time
from datetime import datetime, timedelta

# 计算剩余时间
def calculate_remaining_time(end_time):
    current_time = datetime.now()   # 获取当前时间
    remaining_time = end_time - current_time   # 计算剩余时间
    return remaining_time

# 计算总共工作时间
def total_second(start_time, end_time):
    now_hour = end_time.hour - start_time.hour
    return now_hour * 60 * 60

# 显示进度条和剩余时间
def display_progress_and_time(progress, remaining_time):
    progress_bar_length = 40
    filled_length = int(progress * progress_bar_length)
    remaining_length = progress_bar_length - filled_length

    progress_bar = '█' * filled_length + '-' * remaining_length
    percentage = progress * 100

    print(f'进度:|{progress_bar}| {percentage:.2f}%    距离下班还有:{str(remaining_time)}', end='\r')


def main():
    # 下班时间,这里默认是21点下班
    end_time = datetime.now().replace(hour=21, minute=0, second=0, microsecond=0) 
    # 上班时间,这里默认是9点上班
    start_time = datetime.now().replace(hour=9, minute=0, second=0, microsecond=0)

    while True:
        # 计算进度和剩余时间
        remaining_time = calculate_remaining_time(end_time)
        total_seconds = remaining_time.total_seconds()
        progress = 1 - (total_seconds / total_second(start_time, end_time))

        if progress >= 1:
            print('\n该下班啦!')
            break

        display_progress_and_time(progress, remaining_time)
        time.sleep(1)  # 每秒更新一次进度条和剩余时间

if __name__ == "__main__":
    main()