Python新手学习(十四):保持时间、计划任务和启动程序

17.保持时间、计划任务和启动程序
1)time模块
    time.time() 返回1970年1月1日到现在的秒数。纪元时间戳
    time.ctime() 返回当前时间的字符串描述
      用秒数相减可得到运行时间
    测试程序:test_1701.py

import time,sys
def calcProd():
    # Caluculate the product of the first 100,000 numbers.
    product = 1
    for i in range(1,100000):
        product = product * i
    return product

startTime =time.time()
prod = calcProd()
endTime = time.time()
sys.set_int_max_str_digits(1000000)
print('The result is %s digits long.' % (len(str(prod))))
print('Took %s seconds to calculate.' % (endTime - startTime))

      测试100000万阶乘的运行时间和结果的位数
      结果位数超过str()上限,要用sys.set_int_max_str_digits(1000000)拓位
    time.sleep() 程序暂停的秒数
2)数字四舍五入
    round() 四舍四入
    第一个参数是数值,第二个参数是保留位数,参数为正保留小数位,为负保留整数位
3)项目:超级秒表
    测试程序:test_1702.py

#! python3 
# stopwatch.py - A simple stopwatch program.

import time

# display the program's instructions.
print('Press ENTER to begin。 Afterward,press ENTER to "click" the stopwatch. Press Ctrl-C to quit.')
input()                     # press Enter to begin
print('Started.')
startTime = time.time()     # get the first lap's start time
lastTime = startTime
lapNum =1

# Start tracking the lap times.
try:
    while True:
        input()
        lapTime = round(time.time() - lastTime,2)
        totalTime = round(time.time() - startTime,2)
        print('Lap #%s: %s (%s)' % (
            lapNum,totalTime,lapTime),end='')
        lapNum += 1
        lastTime = time.time()          #reset the last lap time
except KeyboardInterrupt:
    # Handle the Ctrl-C exception to keep its error message from displaying.
    print('\nDone.')

4)datetime模块
    datetime.datetime.now() 显示当前的日期时间。
    datetime.datetime(2024,4,28,11,21,18,0)
    year month day hour minute second
    datetime.datetime.fromtimestamp(1000000)
    datetime.timedelta() 用于表示时段
    暂停直到特定日期 
    datetime.datetime.strftime() 将datetime对象转换成字符串
    datetime.datetime.strptime() 将字符串转换为datetime
5)Python的时间函数
    time datetime timedelta time.time() time.sleep() 
    datetime.datetime .now() .fromtimestamp()
6)多线程
    threading模块
    threadObj= threading.Thread()
    threadObj.start()
    测试程序:test_1703.py

import threading,time

print('Start of program.')

def takeANap():
    time.sleep(5)
    print('Wake up!!')

threadObj = threading.Thread(target=takeANap)
threadObj.start()

print('End of program.')

    向线程的目标函数传递参数
    target args=[ ]    kwargs={‘para’:’vale’}
    线程并发
7)项目:多线程XKCD下载程序
    略。
8)从python启动其它程序
    subprocess模块
    subprocess.Popen()
    poll() 轮询       wait()阻塞等待
    Popen传递命令行参数,Popen([subproc,argv1,argv2])
    指定时间启动 Task Scheduler launchd cron
    打开网站 webbowser.open()
    运行其它python脚本 Popen([‘py’,’hello.py’])
    默认应用程序打开文件 Popen([‘start’,’hello.txt’],shell=True)
9)项目:简单的倒计时程序
    测试程序:test_1704.py

#! python3
# countdown.py - A simple countdown script.

import time,subprocess,os

os.chdir('d:/temp')

timeLeft =10
while timeLeft > 0:
    print(timeLeft)
    time.sleep(1)
    timeLeft = timeLeft - 1

# At the end of the countdown,play a sound file.
subprocess.Popen(['start','alarm.wav'],shell=True)
  • 4
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值