time、datetime和多线程

time模块用于取得Unix纪元时间戳,并加以处理

import time
print(time.time())
print(round(time.time(),2))#四舍五入获取当前时间

#超级秒表
print('Press ENTER to begin.Afterwards, press ENTER to "click" the stopswatch.')
print('Press Ctrl-C to quit.')

input()
print('Started.')
startTime = time.time()
lastTime = startTime

lapNum = 1

try:
    while True:
        input()
        lapTime = round(time.time() - lastTime,2)
        totalTime = round(time.time() - startTime,2)
        print('Lap #%s: %s(%s)'%(lapNum,lapTime,totalTime),end ='')
        lapNum += 1
        lastTime = time.time()
except KeyboardInterrupt:
    print('\nDone')

如果更方便的格式显示日期,或对日期进行算术运算,就应该使用datetime模块

datetime模块有自己的datetime数据类型,datetime值表示一个特定的时刻

import datetime

print(datetime.datetime.now())

dt = datetime.datetime.now()
print(dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second)#dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second(年、月、日、时、分、秒)

调用datetime.datetime.now()返回一个datetime对象,表示当前的日期和时间,这个对象包括当前时刻的年、月、日、时、分、秒、微妙

也可以利用datetime.datetime()函数,向它传入代表年、月、日、时、分、秒整数,得到特定datetime对象

Unix纪元时间戳可以通过datetime.datetime.fromtimestamp(),转化为datetime对象,datetime对象的日期和时间将根据本地时区转换

datetime对象可以通过比较操作符进行比较,弄清楚谁在前面,后面的datetime对象是更大值

print(datetime.datetime.fromtimestamp(time.time()))

if datetime.datetime(2017,12,21,12,12,12) >= datetime.datetime.fromtimestamp(time.time()):
    print("True")
else:
    print("False")


timedelta数据类型

datetime模块还提供了timedelta数据类型,它表示一段时间,而不是一个时刻

要创建timedelta对象,就需要调用datetime.timedelta()函数,datetime.timedelta()函数接受关键字参数weeks、days、hours、minutes、seconds
、milliseconds和microseconds,没有month和year关键词参数,因为“月”和“年”是可变的时间,依赖与特定的月份和年份。

timedelta对象用于的总时间以天、秒、毫秒来表示,这些数字分别保存在days、seconds和Microseconds属性中,

timedelta对象调用total_seconds()方法返回只以秒表示的时间,将一个timedelta对象传入str()将返回格式良好的,人类可读的字符串表示

delta = datetime.timedelta(weeks = 2,days = 2,hours = 12,minutes = 50,seconds = 45)

print(delta)
print(str(delta))

print(delta.days,delta.seconds,delta.microseconds)

print(delta.total_seconds())
算术运算符可以用于对datetime值进行日期运算

利用+/-运算符,timedetla对象与datetime对象或者其他timedetla对象相加减;
利用*和/运算符,timedetla对象可以乘以或者除以整数或者浮点数

dtt = datetime.datetime.now() + delta

print(dtt)

print(datetime.datetime.now() - delta)

print(delta*2)
print(delta*2.14)

print(delta/2)
print(delta/2.14)


暂停直至特定时间

startRunTime = datetime.datetime(2017,6,22,14,36,0)
while datetime.datetime.now() < startRunTime:
    time.sleep(1)
print("startRunTime......")

将datetime对象转变为字符串
利用strftime()方法,可以将datetime对象显示成字符串,向strftime()传入一个定制的格式字符串,其中包含格式化指定(以及任何需要的斜线
、冒号等),strftime()将返回一个格式化的字符串

完整的strftime()指令:
下面是详细参数:
t:这是要格式化秒的时间。
format:这是将用于格式化给定的时间指令。以下指令可以嵌入在格式字符串。

指令:
%a - 星期几的简写名称
%A - 星期名全称
%b - 月份名称缩写(英文)
%B - 完整的月份名称(英文)
%c - 首选的日期和时间的表示
%C - 世纪值(除以100年,范围从00到99)
%d - 月份中的一天(01至31日)
%D - 和%m /%d /%y相同
%e - (1到31月的一天)
%g - %G一样,但没有世纪,年份
%G - 4位数的年份对应的ISO星期数(参见%的V)。
%H - 小时,使用24小时时钟(00至23)
%h - 等同与%b
%I - 小时,使用12小时时钟(01到12)
%j - 一天的一年(001到366)
%m - 月份(01到12)
%M - 分钟
%n - 换行符
%p - 无论是上午或下午,根据给定的时间价值
%r - 时间在上午和下午符号
%R - 24小时符号的时间,不含有秒
%S - 秒(00-59)
%t - 制表符
%T - 当前时间,和%H:%M:%S的
%U - 等同于%V和%W
%u - 平日作为一个数字(1至7),星期一= 1。警告:在Sun公司的Solaris星期日=1
%V - 本年度ISO 8601的周数(01至53),其中第1周是在本年度至少4天的第一个星期,星期一作为一周的第一天
%W - 当年的周数,第一周的第一天开始的第一个星期一
%w - 星期作为一个小数,星期日= 0 %X - 首选日表示,没有时间
%x - 首选的时间表示没有日期,"06/22/17"
%y - 没有世纪的年份(范围从00到99)
%Y - 包括世纪的一年 %Z或%Z - 时区名或缩写
%% - 文字上的字符%
'''

#datetime.datetime.now()可以被替换为datetime.datetime(2015,6,18,13,25,34)
print(datetime.datetime.now().strftime('%Y/%m/%d %I:%M:%S %R'))
print(datetime.datetime.now().strftime('%Y/%m/%d %I:%M:%S %p'))

print(datetime.datetime.now().strftime('%Y/%m/%d %R'))

print(datetime.datetime.now().strftime('%V'))
print(datetime.datetime.now().strftime('%W'))
print(datetime.datetime.now().strftime('%h'))
print(datetime.datetime.now().strftime('%T'))

print(datetime.datetime.now().strftime('%x'))

将字符串转换成datetime对象

需要爱调用datetime.datetime.strptime(),striptime()函数和strftime()函数相反,定制的格式字符串使用相同的指定,
必须将格式字符串传入strptime(),这样它就知道如何解析和理解字符串

print(datetime.datetime.strptime('2017/06/22 07:16:14 PM','%Y/%m/%d %I:%M:%S %p'))

多线程

使用threading模块,在单独的线程中执行延迟或安排其他代码,这个单独的进程将因为time.sleep()调用而暂停,同时,程序可以在原来的线程中做其他工作

要得到单独的线程,首先要调用threading.Thread()函数,生成一个Thread对象

import threading

print('Starting of program.')


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

threadObj = threading.Thread(target = takeANap)#调用threading.Thread()函数,并传入关键字参数target=takeANap,而不是target=takeANap(),创建threadObj对象
threadObj.start()#创建新的线程,并开始在新的线程中执行目标函数

print('End of program.')

向线程的目标函数传递参数

如果想在新线程中运行的目标函数有参数,可以将目标函数的参数传入threading.Thread()函数

print('Cats','Dags','Frogs',sep = ' & ')
threadObjOne = threading.Thread(target = print,args = ['Cats','Dags','Frogs'],kwargs = {'sep':' & '})
threadObjOne.start()

从python启动其他程序

利用内建的subprocess模块中的Popen()函数,Python程序可以启动计算机中的其他程序

Popen()函数中的P代表Process进程,参数是程序的文件路径,返回值是Popen对象

每一个进程可以有多个线程,不像线程,进程无法读取另一个进程的变量

import subprocess
subprocess.Popen('C:\\Users\\Nick\\AppData\\Roaming\\360se6\\Application\\360se.exe')
#返回值是一个Popen对象,<subprocess.Popen object at 0x02C007B0>

Popen 对象有两个非常有用的函数poll()和wait()

poll()是查看进程是否正在运行;如果进程在poll()方法调用时正在运行,poll()返回None,如果该进程以停止运行,他就会返回程序的整数退出代码,

退出代码用于说明进程无错误终止(退出代码为0),还是一个错误导致进程终止(退出代码非零,通常为1)


wait()方法就像是等待你的朋友执行完他的代码,然后在执行你的代码

wait()方法将阻塞,直到启动的进程终止,如果你希望你的程序暂停,直到用户完成其他程序
wait()的返回值是进程的整数退出代码

import subprocess
sunprocessObj = subprocess.Popen('C:\\Users\\Nick\\AppData\\Roaming\\360se6\\Application\\360se.exe')
print(sunprocessObj.poll())
print(sunprocessObj.wait())
time.sleep(5)
print(sunprocessObj.poll())

Popen()函数创建进程时,可以向进程传递命令行参数,要做到这一点,向Popen()传递一个列表,作为唯一参数,列表的第一字符串是要启动的程序的可执行文件名,
后续的字符串将是程序启动时,传递给该程序的命令行参数
subprocess.Popen(['C:\\Program Files (x86)\\Sublime Text3\\sublime_text.exe','C:\\Users\\Nick\\Desktop\\solr方法.txt'])

使用默认的应用程序打开文件

每一个操作系统中,都有一个程序,其行为等价于双击文档文件打开它,

在windows,这就是start程序;在OSX中,这就是open程序;在Ubuntu Linux上,这就是see程序

subprocess.Popen(['start','C:\\Users\\Nick\\Desktop\\solr方法.txt'],shell=True)

#倒计时
timeLeft = 60

while timeLeft > 0:
    print(timeLeft,end = ' ')
    time.sleep(1)
    timeLeft = timeLeft - 1
subprocess.Popen(['start','C:\\Users\\Nick\\Desktop\\感觉静谧.mp3'],shell=True)




发布了32 篇原创文章 · 获赞 5 · 访问量 5万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章