time datetime json模組
阿新 • • 發佈:2018-11-09
time模組
import os
import time
time1 = os.path.getatime('/etc/group')
print(time1) #得到的time1時一個時間綴
tuple_time = time.localtime()
print(tuple_time) #得到的是一個元組時間
year = tuple_time.tm_year #獲取元組時間中的年份
print(year)
month = tuple_time.tm_mon #獲取元組時間中的月份
print(month)
#常用的時間轉換
print(time.mktime(tuple_time)) #將元組時間轉換成時間綴
print(time.strftime('%m-%d')) #將元組的時間轉換成字串格式
print(time.strftime('%T')) #一字串格式顯示當下時間
print(time.strftime('%F')) #以字串格式i顯示當下日期
s = '2018-10-10'
print(time.strptime(s,'%Y-%m-%d')) #將字串時間轉換成元組,沒有的預設為0
l = '12:12:12'
print(time.strptime(l,'%H:%M:%S'))
獲取到的時間綴:
獲取到的時間組:
獲取到的時間:
將獲取到的時間轉化為字串形式:
將獲取的時間轉換為元組形式:
命名元組
from collections import namedtuple
home = namedtuple('member',['zhang','liu','yan']) #定義帶有欄位名的元組
u = home('zhangpeidong','liiuu','uanyan') #向元組裡新增內容
print(u)
print(u.zhang)
datatime 時間模組
datatime 模組中的timedalta支援時間的加減
from datetime import date, time, timedelta, datetime
print(date.today()) #獲取當前的日期,並以字串格式返回
d = date.today()
print(d)
dalta = timedelta(days=4)
print(d-dalta) #delta支援加減一個時間的間隔
s = datetime.today()
print(s)
s1 = timedelta(hours=5)
print(s-s1) #返回的是一個新的日期物件
應用監控系統
import os
from datetime import datetime
import psutil
print('主機資訊'.center(50,'*'))
print(os.uname())
info = os.uname()
print('''
1.作業系統:%s
2.主機名:%s
3.核心版本:%s
4.硬體架構:%s
''' %(info.sysname,info.nodename,info.release,info.machine))
print('開機時間'.center(50,'*'))
start_time = psutil.boot_time()
start_time = datetime.fromtimestamp(start_time) #返回的也是一個物件
now_time = datetime.now() #datetime 返回的是一個datetime實力化物件
delta_time = now_time - start_time
print('''
1.開機時間:%s
2.當前時間:%s
3.開機時長:%s
''' %(start_time,str(now_time).split('.')[0],str(delta_time).split('.')[0]))
print('當前的登陸使用者'.center(50,'*'))
username = {i.name for i in psutil.users()}
print(username)
結果顯示:
json模組
import json
d = {'name':'fentiao'}
json_str = json.dumps(d)
print(json_str,type(json_str)) #json 模組將python中的其他資料型別變換成字串
a = json.loads(json_str)
print(a,type(a)) #json通過loads方法進行解碼為原有的資料型別
#將python物件變換為json的字串格式寫入檔案中
with open('json.txt','w') as f:
json.dump(d,f)
#將檔案中的json字串解碼為python物件
with open('json.txt') as e:
json_fiel = json.load(e)
print(json_fiel,type(json_fiel))
結果顯示: