1. 程式人生 > >Python學習—常用時間類與命名元組

Python學習—常用時間類與命名元組

間隔 獲取時間 主機信息 8.0 我們 可能 版本 常用 cal

常用時間類與命名元組

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 os
import time

info = 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 2018
Sat Aug 25 17:31:38 2018
Sat Aug 25 17:31:38 2018
"""

1.time類

import time
import 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-08
2018-09-08
10:37:06
2018-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 datetime

d = datetime.date.today()
print(d)
"""
輸出:
2018-09-08
"""

distance = datetime.timedelta(days=5)   #間隔5天
print(d - distance)     #當前時間後退5天
print(d + distance)     #當前時間前進5天
"""
輸出:
2018-09-03
2018-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.324586
2018-09-08 05:29:40.324586
2018-09-08 15:29:40.324586
"""

實例
實現監控:
1.獲取當前主機信息,包含操作系統名字,主機名字,內核版本,硬件架構
2.開機時間,當前時間,開機使用時長
3.當前登陸用戶

"""

使用虛擬環境 python3.7
安裝了psutil模塊
"""
import datetime
import psutil
import os

info = 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 namedtuple

Friend = namedtuple("Friend", [‘name‘, ‘age‘, ‘email‘])

f1 = Friend(‘hahaha‘, 33, ‘[email protected]‘)
print(f1)
print(f1.name,f1.age,f1.email)

f2 = Friend(name=‘wowowo‘, email=‘[email protected]‘, age=30)
print(f2)

name, age, email = f2
print(name, age, email)

運行結果:

Friend(name=‘hahaha‘, age=33, email=‘[email protected]‘)
hahaha 33 [email protected]
Friend(name=‘wowowo‘, age=30, email=‘[email protected]‘)
wowowo 30 [email protected]

Python學習—常用時間類與命名元組