Python学习—常用时间类与命名元组
1. 常用时间类
date 日期类
time 时间类
datetime
timedelat 时间间隔
2. 一些术语和约定的解释:
1.时间戳(timestamp)的方式:通常来说,时间戳表示的是从1970年1月1日开始按秒计算的偏移量(time.gmtime(0))此模块中的函数无法处理1970纪元年以前的时间或太遥远的未来(处理极限取决于C函数库,对于32位系统而言,是2038年)
2.UTC(Coordinated Universal Time,世界协调时)也叫格林威治天文时间,是世界标准时间.在我国为UTC+8
3.DST(Daylight Saving Time)即夏令时
4.时间元组(time.struct_time对象, time.localtime方法)
5.字符串时间(time.ctime)
补充一下关于os模块获取文件时间信息的方法
import osimport timeinfo = os.uname() #当前主机信息print(info)atime = os.path.getatime('/etc/passwd') #access_time 最近一次访问时间,时间戳ctime = os.path.getctime('/etc/passwd') #change_time 最近一次修改时间,时间戳mtime = os.path.getmtime('/etc/passwd') #modify_time 最近一次修改时间,时间戳print(atime,'\n',ctime,'\n',mtime)"""输出:1536312601.7119284 1535189498.464139 1535189498.4471388"""#time.ctime返回当前时间,也具有将时间戳改变格式的功能print(time.ctime(atime))print(time.ctime(ctime))print(time.ctime(mtime))"""输出:Fri Sep 7 17:30:01 2018Sat Aug 25 17:31:38 2018Sat Aug 25 17:31:38 2018"""
1.time类
import timeimport os#time.localtime()返回一个类似元组的结构,里面是时间各部分组成属性print(time.localtime())"""输出:time.struct_time(tm_year=2018, tm_mon=9, tm_mday=8, tm_hour=9, tm_min=47, tm_sec=57, tm_wday=5, tm_yday=251, tm_isdst=0)"""ctime = os.path.getctime('/etc/group')#time.localtime()也可以将时间戳转换为类似元组结构,里面是时间各部分组成属性.可以访问这些属性t = time.localtime(ctime)print(t)print(t.tm_year,t.tm_mon,t.tm_mday)"""输出:time.struct_time(tm_year=2018, tm_mon=8, tm_mday=25, tm_hour=17, tm_min=31, tm_sec=38, tm_wday=5, tm_yday=237, tm_isdst=0)2018 8 25"""t = time.ctime(ctime)print(t)"""输出:Sat Aug 25 17:31:38 2018"""#保存到文件with open('data.txt','a+') as f: f.write(t)"""*****把类似元组结构的时间 转换为时间戳格式*****time.mktime()"""t = time.localtime()t2 = time.mktime(t)print(t2)"""输出:1536372128.0""""""*****自定义时间格式*****time.strftime()*****在Python内部的strftime()方法说明*****def strftime(format, p_tuple=None): # real signature unknown; restored from __doc__ # strftime(format[, tuple]) -> string # # Convert a time tuple to a string according to a format specification. # See the library reference manual for formatting codes. When the time tuple # is not present, current time as returned by localtime() is used. # # Commonly used format codes: # # %Y Year with century as a decimal number. # %m Month as a decimal number [01,12]. # %d Day of the month as a decimal number [01,31]. # %H Hour (24-hour clock) as a decimal number [00,23]. # %M Minute as a decimal number [00,59]. # %S Second as a decimal number [00,61]. # %z Time zone offset from UTC. # %a Locale's abbreviated weekday name. # %A Locale's full weekday name. # %b Locale's abbreviated month name. # %B Locale's full month name. # %c Locale's appropriate date and time representation. # %I Hour (12-hour clock) as a decimal number [01,12]. # %p Locale's equivalent of either AM or PM."""print(time.strftime('%m-%d'))print(time.strftime('%Y-%m-%d'))print(time.strftime('%T'))print(time.strftime('%F'))"""输出:09-082018-09-0810:37:062018-09-08""""""*****字符串格式转为元组结构*****time.strptime()"""s = '2018-10-10'print(time.strptime(s, '%Y-%m-%d'))s_time = '12:12:30'print(time.strptime(s_time, '%H:%M:%S'))"""输出:time.struct_time(tm_year=2018, tm_mon=10, tm_mday=10, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=283, tm_isdst=-1)time.struct_time(tm_year=1900, tm_mon=1, tm_mday=1, tm_hour=12, tm_min=12, tm_sec=30, tm_wday=0, tm_yday=1, tm_isdst=-1)"""
2.datetime类
import datetimed = datetime.date.today()print(d)"""输出:2018-09-08"""distance = datetime.timedelta(days=5) #间隔5天print(d - distance) #当前时间后退5天print(d + distance) #当前时间前进5天"""输出:2018-09-032018-09-13"""d = datetime.datetime.now()print(d)distance = datetime.timedelta(hours=5) #间隔5小时print(d - distance) #当前时间后退5小时print(d + distance) #当前时间前进5小时"""输出:2018-09-08 10:29:40.3245862018-09-08 05:29:40.3245862018-09-08 15:29:40.324586"""
实例
实现监控:
1.获取当前主机信息,包含操作系统名字,主机名字,内核版本,硬件架构
2.开机时间,当前时间,开机使用时长
3.当前登陆用户
"""使用虚拟环境 python3.7安装了psutil模块"""import datetimeimport psutilimport osinfo = os.uname()"""uname()返回信息:posix.uname_result(sysname='Linux', nodename='myhost', release='3.10.0-514.el7.x86_64', version='#1 SMP Wed Oct 19 11:24:13 EDT 2016', machine='x86_64')"""print('主机信息'.center(40,'*'))print(""" 操作系统:%s 主机名字:%s 内核版本:%s 硬件架构:%s""" %(info.sysname,info.nodename,info.release,info.machine))#获取开机时间boot_time = psutil.boot_time()"""boot_time()返回信息:(一个开机时间点的时间戳)1536367043.0""""""将时间戳转换为字符串格式:1.time.ctime()2.datetime.datetime.fromtimestamp()"""boot_time = datetime.datetime.fromtimestamp(boot_time)"""boot_time的值为:2018-09-08 08:37:23"""#获取当前时间now_time = datetime.datetime.now()#获取时间差time = now_time - boot_time"""获取到的当前时间:2018-09-08 11:24:20.330670获取到的时间差:2:46:57.330670""""""用字符串的方法去掉毫秒部分"""now_time = str(now_time).split('.')[0]time = str(time).split('.')[0]print('开机信息'.center(40,'*'))print(""" 当前时间:%s 开机时间:%s 运行时间:%s""" %(now_time,boot_time,time))#获取登陆的用户详细信息users = psutil.users()"""users()返回的结果:(类似列表结构)[suser(name='kiosk', terminal=':0', host='localhost', started=1536367104.0, pid=1654), suser(name='kiosk', terminal='pts/0', host='localhost', started=1536367360.0, pid=2636)]""""""用列表生成式获取我们想要的结果,但是里面会有重复的记录,这是因为同一个用户可能开了多个shell所以我们直接用集合,来达到去重的目的"""users = {'%s %s' %(user.name,user.host) for user in users}print('登陆用户'.center(40,'*'))for user in users: print('\t %s' %user)
程序运行结果:
******************主机信息****************** 操作系统:Linux 主机名字:myhost 内核版本:3.10.0-514.el7.x86_64 硬件架构:x86_64******************开机信息****************** 当前时间:2018-09-08 11:42:48 开机时间:2018-09-08 08:37:23 运行时间:3:05:25******************登陆用户****************** kiosk localhost
3.命名元组namedtuple
namedtuple类位于collections模块,namedtuple是继承自tuple的子类。namedtuple和tuple比,有更多更酷的特性。namedtuple创建一个和tuple类似的对象,而且对象拥有可以访问的属性。这对象更像带有数据属性的类,不过数据属性是只读的。namedtuple能够用来创建类似于元组的数据类型,除了能够用索引来访问数据,能够迭代,还能够方便的通过属性名来访问数据。在python中,传统的tuple类似于数组,只能通过下表来访问各个元素,我们还需要注释每个下表代表什么数据。通过使用namedtuple,每个元素有了自己的名字。类似于C语言中的struct,这样数据的意义就可以一目了然。
from collections import namedtupleFriend = namedtuple("Friend", ['name', 'age', 'email'])f1 = Friend('hahaha', 33, 'hahaha@163.com')print(f1)print(f1.name,f1.age,f1.email)f2 = Friend(name='wowowo', email='wowowo@sina.com', age=30)print(f2)name, age, email = f2print(name, age, email)
运行结果:
Friend(name='hahaha', age=33, email='hahaha@163.com')hahaha 33 hahaha@163.comFriend(name='wowowo', age=30, email='wowowo@sina.com')wowowo 30 wowowo@sina.com
声明:本站所有文章资源内容,如无特殊说明或标注,均为采集网络资源。如若本站内容侵犯了原著者的合法权益,可联系本站删除。