【python程序设计】time库和文本进度条#181020

本文深入讲解了Python中time库的使用方法,涵盖了时间获取、时间格式化和程序计时等功能,详细介绍了time(), strftime(), perf_counter()等函数,并通过实例演示了如何在Python程序中进行时间操作。

time库的使用

# time库包括三类函数

- 时间获取:time()	ctime()	gmtime()
- 时间格式化:strftime()	strptime()
- 程序计时:sleep()	perf_counter()
  • 时间获取
time()获取当前时间戳,即计算机内部时间值,浮点数
表示从1970年1月1日0点0分0秒开始到现在

>>> import time
>>> time.time()
1540037306.0050652

2018.10.20 - 1970.01.01 = 48.09.19
60 * 60 * 24 * 30 * 12 = 31,104,000
48 * 31,104,000=1,244,160,000
>>> time.ctime()
'Sat Oct 20 20:18:45 2018'

周 月 日 时:分:秒 年
>>> time.gmtime()
time.struct_time(tm_year=2018, tm_mon=10, tm_mday=20, tm_hour=12, tm_min=20, tm_sec=37, tm_wday=5, tm_yday=293, tm_isdst=0)

计算机可识别模式
  • 时间格式化
strftime(tpl,ts)
tpl是格式化模板字符串,用来定义输出效果
ts是计算机内部时间类型变量

>>> t = time.gmtime()
>>> time.strftime("%Y-%m-%d %H:%M:%S",t)
'2018-10-20 12:23:28'

%Y年份,0000~9999
%m月份,01~12
%B月份名称,January~December
%b月份名称缩写,Jan~Dec
%d日期,01~31
%A星期,Monday~Sunday
%a星期缩写,Mon~Sun
%H小时(24),00~23
%h小时(12),01~12
%p上/下午,AM,PM
%M分钟,00~59
%S秒,00~59
strptime(str,tpl)

>>> timeStr = '2018-10-20 12:23:28'
>>> time.strptime(timeStr,"%Y-%m-%d %H:%M:%S")
time.struct_time(tm_year=2018, tm_mon=10, tm_mday=20, tm_hour=12, tm_min=23, tm_sec=28, tm_wday=5, tm_yday=293, tm_isdst=-1)
  • 程序计时
程序计时指测量起止动作所经历时间的过程
测量时间:perf_counter()
产生时间:sleep()

perf_counter()
返回一个CPU级别的精确时间计数值,单位为s
由于计算值起点不确定,连续调用差值才有意义

>>> start = time.perf_counter()
>>> start
2041.101892374
>>> end = time.perf_counter()
>>> end
2070.363240708
>>> end -start
29.261348333999877

>>> time.perf_counter() - time.perf_counter()
0.0

测试程序运行的时间
sleep(s)
s拟休眠的时间,单位是秒,可以是浮点数

>>> def wait():
	time.sleep(3.3)

	
>>> wait()

程序将等待3.3秒后再退出

文本进度条

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

#TestProBarV1.py

import time

scale = 10

print("------执行开始------")

for i in range(scale + 1):
    a = '#' * i
    b = '.' * (scale - i)
    c = (i / scale) * 100
    print("{:^3.0f}%[{}->{}]".format(c,a,b))
    time.sleep(0.1)
print("------执行结束------")


====================== RESTART: C:\Python3.7.0\test.py ======================
------执行开始------
 0 %[->..........]
10 %[#->.........]
20 %[##->........]
30 %[###->.......]
40 %[####->......]
50 %[#####->.....]
60 %[######->....]
70 %[#######->...]
80 %[########->..]
90 %[#########->.]
100%[##########->]
------执行结束------
  • 单行刷新
刷新的本质:用后打印的字符覆盖之前的字符
不能换行:print()需要被控制
要能回退:打印后光标退回到之前的位置\r

#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

#TestProBarV1.py

import time

for i in range(101):
    print("\r{:3}%".format(i),end="")
    time.sleep(0.1)


====================== RESTART: C:\Python3.7.0\test.py ======================

  0%
  1%
  2%
  3%
  4%
  5%
  6%
  7%
  8%
  9%
 10%
 11%
 12%
 13%
 14%
 15%
 16%
 17%
 18%
 19%
 20%
 21%
 22%
 23%
 24%
 25%
 26%
 27%
 28%
 29%
 30%
 31%
 32%
 33%
 34%
 35%
 36%
 37%
 38%
 39%
 40%
 41%
 42%
 43%
 44%
 45%
 46%
 47%
 48%
 49%
 50%
 51%
 52%
 53%
 54%
 55%
 56%
 57%
 58%
 59%
 60%
 61%
 62%
 63%
 64%
 65%
 66%
 67%
 68%
 69%
 70%
 71%
 72%
 73%
 74%
 75%
 76%
 77%
 78%
 79%
 80%
 81%
 82%
 83%
 84%
 85%
 86%
 87%
 88%
 89%
 90%
 91%
 92%
 93%
 94%
 95%
 96%
 97%
 98%
 99%
100%

使用IDLE输出会,因为这是开发环境下


Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import time
>>> for i in range(101):
...     print("\r{:3}%".format(i),end="")
...     time.sleep(0.1)
...
100%

使用窗口模式下输出则看到从0%到100%
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

#TestProBarV1.py

import time

scale = 50

print("执行开始".center(scale//2,"-"))
start = time.perf_counter()
for i in range(scale + 1):
    a = '#' * i
    b = '.' * (scale - i)
    c = (i / scale) * 100
    dur = time.perf_counter() - start
    print("\r{:^3.0f}%[{}->{}]{:.2f}s".format(c,a,b,dur),end='')
    time.sleep(0.1)
print("\n"+"执行结束".center(scale//2,'-'))


Microsoft Windows [版本 10.0.17134.345]
(c) 2018 Microsoft Corporation。保留所有权利。

C:\Windows\System32> path=%path%;D:\Python\Python37\
C:\Windows\System32>cd C:\Python3.7.0
C:\Python3.7.0>python test.py
-----------执行开始----------
100%[##################################################->]5.05s
-----------执行结束----------
Linear	coonstant	f(x) = x
Early Pause	Speeds up	f(x) = x+(1-sin(x*pai*2+pai/2)/-8
Late Pause	Slows down	f(x) = x+(1-sin(x*pai*2+pai)/8
Slow Wavy	Constant	f(x) = x+sin(x*pai*5)/20
Fast Wavy	Constant	f(x) = x+sin(x*pai*20)/80
Power	Speed up	f(x) = (x+(1-x)*0.03)^2
Inverse Power	Slows down	f(x) = 1+(1-x)^1.5*-1
Fast Power	Speeds up	f(x) = (x+(1-x)/2)^2
Inverse Fast Power	Slows down	f(x) = 1+(1-x)^3*-1

  • 关于刷新
主要靠\r和end=''
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-

#TestProBarV1.py

import time

for i in range(100):
    print("\r",i,end='')
    time.sleep(0.1)

C:\Python3.7.0>python test.py
 99

转载于:https://my.oschina.net/hellopasswd/blog/2250012

<think>嗯,用户想用Python设计一个特别的自定义进度条。我之前学过一些关于进度条的知识,记得有几种方法可以实现。首先,可能需要用基本的print函数来覆盖当前行,这样进度条能动态更新。然后,可能需要用到一些第三方,比如tqdm,它们提供了很多内置的样式功能。不过用户想要的是自定义样式,所以可能需要自己动手写代码。 首先,用户提到的引用中有几个例子,比如使用sys.stdout.write\r来回到行首,这样每次更新进度条的时候不会换行。还有用不同的字符来填充进度条,比如星号或者方块字符。比如在引用3中,有一个例子用的是&#39;▋&#39;字符,看起来挺特别的。这可能是一个方向。 然后,用户可能需要考虑颜色动态效果。比如引用2提到了动态显示进度条,可能需要用ANSI转义码来改变颜色或者移动光标的位置。不过ANSI码可能在部分终端不支持,需要测试一下。不过现在大多数终端应该都支持基本的颜色设置。 另外,引用4中提到了自定义进度条的结构,包括定义函数来计算进度百分比,构造进度条字符串,然后实时更新。这可能涉及到进度条的长度计算,比如总长度是50个字符,已完成的长度根据进度比例计算,剩下的用空格填充。然后还要显示百分比,可能还有剩余时间或已用时间。 用户可能需要更复杂的功能,比如在进度条旁边显示当前处理的任务名称,或者添加多个进度条同时运行。这时候可能需要更复杂的,比如rich,它支持丰富的样式布局,不过用户可能需要自己定制的话,可能还是需要从基础做起。 还有,考虑性能问题,如果进度更新太频繁,可能会导致程序变慢,所以可能需要适当控制更新的频率,比如每完成1%才更新一次,而不是每次循环都更新。 然后,测试不同的样式,比如旋转的指针,或者进度条的颜色变化。比如在进度达到50%的时候变成黄色,完成时变成绿色。这可能需要根据进度值来改变ANSI颜色代码。 可能需要分步骤来回答用户的问题。首先介绍基础方法,使用sys.stdout\r,然后展示如何自定义字符样式,接着加入颜色,最后提到第三方的高级定制。这样用户可以根据需求选择不同的方法。 还要注意用户的问题中的“特别”的定义,可能指的是形状、颜色、动画效果或者附加信息。需要覆盖这些方面,给出不同的示例代码,让用户能够根据自己的需求进行调整。 比如,基础的自定义进度条可以用简单的字符百分比,进阶的可以加入颜色,或者动态变化的图标,比如引用3中的不同形状。然后,可以展示如何添加时间估计,或者进度条的分段样式。 最后,可能需要提醒用户注意终端兼容性,比如某些特殊字符或颜色可能在部分环境下无法正常显示,建议测试后再使用。</think>### 如何用Python实现自定义样式或功能的进度条? 以下是实现自定义进度条的几种方法,涵盖基础到进阶样式,并提供代码示例: --- ### 一、基础文本进度条 **核心原理**:通过`\r`回退光标到行首实现动态更新。 ```python import time import sys def basic_progress(total): for i in range(total + 1): percent = i / total * 100 sys.stdout.write(f&#39;\r[{"▋" * int(percent//2)}{" " * (50 - int(percent//2))}] {percent:.1f}%&#39;) sys.stdout.flush() time.sleep(0.1) basic_progress(100) print("\n完成!") ``` **效果**:`[▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋▋] 100.0%` --- ### 二、自定义符号与颜色 **进阶操作**:使用ANSI转义码添加颜色,修改填充符号。 ```python def colored_progress(total): for i in range(total + 1): percent = i / total * 100 color = "\033[32m" if percent >= 50 else "\033[33m" # 50%以下黄色,以上绿色 bar = f&#39;{color}[{"◆" * int(percent//2)}{"◇" * (50 - int(percent//2))}]\033[0m {percent:.1f}%&#39; sys.stdout.write(f&#39;\r{bar}&#39;) sys.stdout.flush() time.sleep(0.1) colored_progress(100) ``` **效果**:动态颜色变化,符号从`◇`变为`◆`。 --- ### 三、添加时间统计 **功能增强**:显示剩余时间与已用时间。 ```python from datetime import datetime def timed_progress(total): start = datetime.now() for i in range(total + 1): elapsed = (datetime.now() - start).total_seconds() speed = elapsed / (i + 1e-6) remaining = (total - i) * speed bar = f&#39;[{"■" * int(i/2)}{"□" * (50 - int(i/2))}] {i}% | 已用: {elapsed:.1f}s | 剩余: {remaining:.1f}s&#39; sys.stdout.write(f&#39;\r{bar}&#39;) sys.stdout.flush() time.sleep(0.1) timed_progress(100) ``` **效果**:显示进度百分比、已用时间预估剩余时间。 --- ### 四、使用第三方(高级定制) **推荐工具**:`tqdm`支持高度自定义,结合`rich`可添加复杂样式[^3][^4]。 ```python from tqdm import tqdm from time import sleep # 自定义进度条格式 bar_format = "{l_bar}{bar}| {n_fmt}/{total_fmt} [剩余: {remaining}]" for _ in tqdm(range(100), bar_format=bar_format, ncols=80, colour=&#39;green&#39;): sleep(0.1) ``` **功能**:支持颜色、速度显示、ETA估算自定义占位符。 --- ###
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值