Python时间模块与循环控制:从入门到实践
🔥 掌握Python中的时间处理和循环控制,让你的程序更智能、更高效!
📚 前言
在Python编程中,时间处理和循环控制是两个非常重要的基础技能。无论是需要让程序暂停执行、获取当前时间,还是根据条件重复执行代码,都离不开这两个模块的灵活运用。今天,我们就通过两个实战案例,深入浅出地学习time时间模块和while循环的使用。
⏰ 一、Python时间模块(time)
1. 模块导入与基本使用
python
import time print(time) # 查看模块信息
2. 程序暂停:sleep()函数
sleep()函数可以让程序暂停指定的秒数,非常适合制作倒计时、动画效果或控制程序节奏。
python
print(1) time.sleep(2) # 暂停2秒 print(2) time.sleep(2) print(3) time.sleep(2) print(4) time.sleep(2) print(5)
运行效果:每隔2秒打印一个数字,从1到5依次输出。
3. 时间戳(Timestamp)
时间戳指从1970年1月1日 00:00:00 UTC到现在的总秒数,常用于记录时间点和计算时间差。
python
# 获取当前时间戳(浮点数,单位:秒) print(time.time()) # 获取毫秒级时间戳(常用于前端和接口签名) print(int(time.time() * 1000))
4. 获取本地时间:localtime()
localtime()返回一个结构化时间对象,包含年、月、日、时、分、秒等属性。
python
now = time.localtime() print(now.tm_year) # 年份 print(now.tm_mon) # 月份 print(now.tm_mday) # 日 print(now.tm_hour) # 小时 print(now.tm_min) # 分钟 print(now.tm_sec) # 秒
5. 时间戳转时间结构体
python
# 将指定时间戳转换为本地时间 print(time.localtime(946656000)) # 转换为国际标准时间(UTC) print(time.gmtime(946656000))
6. 时间格式化:strftime()
将时间结构体转换为指定格式的字符串,非常实用。
python
now = time.localtime()
# 不同格式输出
print(time.strftime("%Y/%m/%d %H:%M:%S", now)) # 2026/07/15 10:30:00
print(time.strftime("%Y-%m-%d %H:%M:%S", now)) # 2026-07-15 10:30:00
print(time.strftime("%Y年%m月%d日 %H时%M分%S秒", now)) # 2026年07月15日 10时30分00秒
常用格式化符号:
| 符号 | 含义 |
|---|---|
| %Y | 四位年份 |
| %m | 月份(01-12) |
| %d | 日(01-31) |
| %H | 小时(00-23) |
| %M | 分钟(00-59) |
| %S | 秒(00-59) |
7. 字符串转时间结构体:strptime()
将日期字符串解析为时间结构体,便于后续处理。
python
now2 = time.strptime("2026年07月14日 17时37分17秒", "%Y年%m月%d日 %H时%M分%S秒")
print(now2, type(now2))
🔄 二、while循环控制
1. for vs while
-
for循环:适用于已知次数的遍历(如列表、range)
-
while循环:适用于根据条件动态判断是否继续执行
2. while基本语法
python
while 条件:
# 条件为True时执行的代码块
pass
关键点:随着程序运行,条件要能变为False,否则会形成死循环。
3. 实战案例:打印5次"hello world"
方法一:使用标志变量
python
is_running = True
count = 0
while is_running:
print("hello world")
count += 1
if count == 5:
is_running = False
方法二:直接判断条件
python
count = 0
while count < 5:
print("hello world")
count += 1
方法三:死循环+break退出
python
count = 0
while True:
print("hello world")
count += 1
if count == 5:
break
4. 交互式输入案例
模拟一个持续接收用户输入的程序,直到输入"exit"退出:
python
while True:
input_str = input("请输入内容(输入exit退出):")
if input_str == "exit":
print("程序已退出")
break
print("你输入的是:", input_str)
🎯 三、综合实战:倒计时程序
结合time.sleep()和while循环,制作一个简单倒计时:
python
import time
countdown = 10
while countdown > 0:
print(f"倒计时:{countdown}秒")
time.sleep(1)
countdown -= 1
print("🎉 时间到!")
📝 四、总结
| 知识点 | 核心要点 |
|---|---|
time.sleep() | 让程序暂停指定秒数 |
time.time() | 获取时间戳(秒/毫秒) |
time.localtime() | 获取本地时间结构体 |
time.strftime() | 时间结构体 → 格式化字符串 |
time.strptime() | 字符串 → 时间结构体 |
while循环 | 条件为True时持续执行 |
break | 跳出当前循环 |
| 循环控制 | 必须让条件最终变为False,避免死循环 |
💡 五、思考与练习
-
尝试用
while循环打印1到100的所有偶数。 -
编写一个程序,每隔3秒打印一次当前时间,共打印10次。
-
将用户输入的日期字符串(如"2026-07-15")转换为时间戳并输出。
📌 本文代码基于Python 3环境,所有示例均在本地测试通过。如果你有任何疑问或更好的想法,欢迎在评论区交流讨论!
关注我,持续分享Python干货! 🚀
1170



被折叠的 条评论
为什么被折叠?



