Python中常见模块的用法

########常见模块的用法########

## time模块的详述

##  time模块简介

time模块--时间获取和转换
time模块提供各种时间相关的功能
与时间相关的模块有:time,datetime,calendar
这个模块中定义的大部分函数是调用C平台上的同名函数实现

## 一些术语和约定的解释:
 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)

import time
print(time.ctime())
print(time.localtime())

 

##  需求
利用time.time()方法,我们可以计算两个时间点之间的间隔,
但是有些时候我们想要得到/etc/group文件的最后一次修改时间,
对应的年月日这些信息,并保存在文件date.txt文件中

import time
import os

time1 = os.path.getctime('/etc/group')
print(time1)
localTime = time.localtime(time1)
print(localTime)
print(time.ctime(time1))
year = localTime.tm_year
month = localTime.tm_mon
day = localTime[2]
with open('date.txt', 'w+') as f:
    f.write("%d : %d : %d" % (year, month, day))

##. 常用的时间转换
# 把看不懂的时间戳转换为字符串格式
        **自行整理
# 把看不懂的时间戳转换为元组格式
        **自行整理

# 把元组的时间转换为时间戳
import time
tuple_time = time.localtime()
print(time.mktime(tuple_time))

# 把元组的时间转换字符串格式
import  time
print(time.strftime('%m-%d'))
print(time.strftime('%Y-%m-%d'))
print(time.strftime('%T'))
print(time.strftime('%F'))

# 字符串格式转换为元组
import time
s = '2018-10-10'
print(time.strptime(s, '%Y-%m-%d'))
s_time = '12:12:30'
print(time.strptime(s_time, '%H:%M:%S'))

import time

print('把元组的时间转换为时间戳')
time1 = time.localtime()
print(time.mktime(time1))
print('把元组的时间转换字符串格式')
print(time.strftime('%Y/%m/%d'))
print(time.strftime('%T'))
print(time.strftime('%F'))
print('字符串格式转换为元组')
s = '2018-08-08'
print(time.strptime(s, '%Y-%m-%d')[0:3])
s_time = '18:22:16'
print(time.strptime(s_time, '%H:%M:%S')[3:6])

 

## datetime 模块

from datetime import  date
from datetime import  time
from datetime import  datetime
from datetime import  timedelta
# # 获取当前的日期并且以字符串方式返回2018-09-08;
# print(date.today())
# # 对象加或者减一个时间间隔, 返回一个新的日期对象;
# d = date.today()
# print(d)
# delta = timedelta(days=3)
# print(d - delta)
#
# # 需求: 想返回3个月以前的时间;
# 需求: 获取2个小时之前的时间为什么?

from datetime import date
from datetime import time
from datetime import datetime
from datetime import timedelta

d = date.today()
h = datetime.now()
M = timedelta(days=92)
H = timedelta(hours=2)
print(d - M)
print(h - H)

 

## 需求:

    1. 获取当前主机信息, 包含操作系统名, 主机名, 内核版本, 硬件架构等
    2. 获取开机时间和开机时长;
    3. 获取当前登陆用户

import psutil
import os
import time
from datetime import datetime
from psutil._common import suser

info = os.uname()
print(info)
print("1. 主机信息".center(50, '*'))
print("""
    操作系统: %s, 
    主机名: %s, 
    内核版本: %s, 
    硬件架构: %s
""" % (info.sysname, info.nodename, info.release, info.machine))

print("开机时间".center(50, "*"))
boot_time = psutil.boot_time()
boot_time = datetime.fromtimestamp(boot_time)
now_time = datetime.now()
delta_time = now_time - boot_time
delta_time = str(delta_time).split('.')[0]
print("""
    开机时间: %s
    当前时间: %s
    开机时长: %s
""" % (boot_time, now_time, delta_time))

print("当前登陆用户".center(50, '*'))
users = psutil.users()
# print(users, type(users))
users = {"%s %s" %(user.name, user.host)  for user in users}
for user in users:
    print("\t  %s" %(user))

 

## namedtuple新型数据类型

# namedtuple的需求:
因为元组的局限性:不能为元组内部的数据进行命名,所以往往我们并不知道一个元组所要表达的意义,
所以在这里引入了 collections.namedtuple 这个工厂函数,来构造一个带字段名的元组。
具名元组的实例和普通元组消耗的内存一样多,因为字段名都被存在对应的类里面。这个类跟普通的对象
实例比起来也要小一些,因为 Python 不会用 __dict__ 来存放这些实例的属性。


# 如何实现
def namedtuple(typename, field_names, *, verbose=False, rename=False, module=None):
    - typename: 元组名称
    - field_names : 元组中元素的名称
    - rename: 如果元素名称中包含python关键字, 必须设置rename=True

from collections import  namedtuple
from collections import Iterator
from collections import  Counter
User = namedtuple('User', ['name', 'age', 'gender'])
u = User('kobe', 24, 'male')
print(u.name)
print(u.age)
print(u.gender)
print(u)

from collections import  namedtuple
from collections import Iterator
from collections import  Counter

User = namedtuple('User', ['name', 'age', 'gender'])
u = User('kobe', 24, 'male')
print(u.name)
print(u[0])
print(u.age)
print(u.gender)
print(u)

 

## json 模块

## 应用

# import json
# # 将python对象编码成为json的字符串格式;
# d = {'name': 'kobe'}
# jsonStr = json.dumps(d)
# print(jsonStr)
# print(type(jsonStr))
#
# l = [1, 2, 3, 4]
# jsonLi = json.dumps(l)
# print(jsonLi, type(jsonLi))
#
# # 将获取的json字符串解码为python的对象
# pythonDict = json.loads(jsonStr)
# print(pythonDict, type(pythonDict))
#
# # 将将python对象编码成为json的字符串格式并写入文件中;
# with open('json.txt', 'w') as f:
#     json.dump(d, f)
#
# # 将文件中的json字符串解码为python的对象
# with open('json.txt') as f:
#     json_Dict = json.load(f)
#     print(json_Dict, type(json_Dict))

import json

d = {'name': 'kobe'}
jsonStr = json.dumps(d)
print(jsonStr, type(jsonStr))

l = [1, 2, 3, 4]
jsonLi = json.dumps(l)
print(jsonLi, type(jsonLi))

pythondict = json.loads(jsonStr)
print(pythondict, type(pythondict))

with open('json.txt', 'w') as f:
    json.dump(d, f)

with open('json.txt') as f:
    json_Dict = json.load(f)
    print(json_Dict, type(json_Dict))

import json
import string
from random import choice

keys = string.ascii_lowercase
values = string.ascii_letters + string.digits
dict = {choice(keys): choice(values) for i in range(20)}
with open('json.txt', 'w') as f:
    # separators = ("每个元素间的分隔符", “key和value之间的分隔符”)
    json.dump(dict, f, indent=4, sort_keys=True, separators=(';', '='))

## 获取IP对应的地理位置

  根据IP查询所在地、运营商等信息的一些API如下:
    1. 淘宝的API(推荐):http://ip.taobao.com/service/getIpInfo.php?ip=110.84.0.129
    2. 国外freegeoip.net(推荐):http://freegeoip.net/json/110.84.0.129 这个还提供了经纬度信息(但不一定准)
    3. 新浪的API:http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=110.84.0.129
    4. 腾讯的网页查询(返回的非json格式): http://ip.qq.com/cgi-bin/searchip?searchip1=110.84.0.129
    5. ip.cn的网页(返回的非json格式):http://www.ip.cn/index.php?ip=110.84.0.129
    6. ip-api.com: http://ip-api.com/json/110.84.0.129

上述的API接口,大多有一个特点是, 返回的直接是个json格式

# ip = input('IP:')
import json
from urllib.request import urlopen

# ip = '8.8.8.8'
ip = input("请输入查询的IP:")
url = "http://ip.taobao.com/service/getIpInfo.php?ip=%s" %(ip)

# 根据url获取网页的内容, 并且解码为utf-8格式, 识别中文;
text  = urlopen(url).read().decode('utf-8')
# print(text)
# print(type(text))

# 将获取的字符串类型转换为字典, 方便处理
d = json.loads(text)['data']
country = d['country']
city = d['city']
print(country, city)

## difflib 模块

import difflib

file1 = '/etc/passwd'
file2 = '/tmp/passwd'

with open(file1) as f1, open(file2) as f2:
    f1.seek(0, 0)
    text1 = f1.readlines()
    f2.seek(0, 0)
    text2 = f2.readlines()
d = difflib.HtmlDiff()
with open('passwd.txt', 'w') as f:
    f.write(d.make_file(text1, text2))

import  difflib

# ['', '1 line', '2 line']
text1 = '''  
    1. Beautiful is better than ugly.
    2. Explicit is better than implicit.
    3. Simple is better than complex.
    4. Complex is better than complicated.
'''.splitlines(keepends=True)


text2 = '''  
    1. Beautifu  is better than ugly.
    2. Explicit is better than implicit.
    3. Simple is better than complex.
    4. Complex is better than complicated.
'''.splitlines(keepends=True)



# 1. 以字符串方式展示两个文本的不同, 效果如下:
d = difflib.Differ()
result = list(d.compare(text1, text2))
result = " ".join(result)
print(result)
"""
 -     1. Beautiful is better than ugly.
 ?                ^
 +     1. Beautifu  is better than ugly.
 ?                ^
       2. Explicit is better than implicit.
       3. Simple is better than complex.
       4. Complex is better than complicated.
"""

#####################################

猜你喜欢

转载自blog.csdn.net/houzeyu666/article/details/82585300