标签:
Python中称模块,其他软件称类库
先导入,后使用
导入方式:import 模块名称
导入模块:
单模块:import
嵌套在文件夹下:from xxx import xxx
from xxx import xxx as ooo
示例:
# 导入模块 # 导入s4文件 import s4 # 导入lib目录下的commons import lib.commons # 调用模块 # 调用s4文件的login()模块 s4.login() # 调用lib目录下commons文件的f1模块 lib.commons.f1() # 导入s4文件内login模块 from s4 import login loging() # 导入s4文件内所有模块 from s4 import * #导入s4内所有模块
别名设置:
# 导入lib目录下commons文件,设置别名 为lib_commons from lib import commons as lib_commons #导入src目录下commons文件,设置别名 为src_commons from src import commons as src_commons
为什么要有模块:将代码归类
导入模块的依据:import
sys.path
模块名称的重要性:一定不要和内置模块重名
D:\Python\Python_S13_35\day05 #当前路径 D:\Program Files\Python\Python35\python35.zip D:\Program Files\Python\Python35\DLLs D:\Program Files\Python\Python35\lib D:\Program Files\Python\Python35 D:\Program Files\Python\Python35\lib\site-packages #第三方模块路径
pip3 requests
python -m pip install requests #windows下执行 You are using pip version 7.1.2, however version 8.1.2 is available. You should consider upgrading via the ‘python -m pip install --upgrade pip‘ command.
序列化相关
import json import pickle
序列化解释:将python的基本数据类型转换成字符串形式
反序列化:将字符串转换成python的基本数据类型,要求内容必须符合基本数据类型特征
import json
dic = {‘k1‘: "v1"}
print(dic,type(dic))
# 将python基本数据类型转化成字符串形式
result = json.dumps(dic)
print(result,type(result))
s1 = ‘{"k1":123}‘
# 将python字符串形式转化成基本数据类型
dic = json.loads(s1)
print(dic,type(dic))
# requests结合json序列化实例
import requests
import json
response = requests.get(‘http://wthrcdn.etouch.cn/weather_mini?city=北京‘)
response.encoding = ‘utf-8‘
dic = json.loads(response.text) #获取http内容
print(dic, type(dic))
import json li = [11, 22, 33, ] json.dump(li, open(‘db‘, ‘w‘)) li = json.load(open(‘db‘, ‘r‘)) print(li, type(li))
+-------------------+---------------+ | Python | JSON | +===================+===============+ | dict | object | +-------------------+---------------+ | list, tuple | array | +-------------------+---------------+ | str | string | +-------------------+---------------+ | int, float | number | +-------------------+---------------+ | True | true | +-------------------+---------------+ | False | false | +-------------------+---------------+ | None | null |
import pickle li = [11, 22, 33] r = pickle.dumps(li) print(r) result = pickle.loads(r) print(result) # 输出结果 # b‘\x80\x03]q\x00(K\x0bK\x16K!e.‘ # [11, 22, 33] li = [11, 22, 33] pickle.dump(li, open(‘db‘, ‘wb‘)) result = pickle.load(open(‘db‘, ‘rb‘)) print(result) # # 输出结果 # [11, 22, 33]
json 更加适合跨语言,字符串,基本数据类型
pickle,python所有类型的序列化操作,仅适用于python,需要注意版本问题
常用:取时间戳
import time print(time.time()) print(time.mktime(time.localtime())) print(time.gmtime()) #可加时间戳参数 print(time.localtime()) #可加时间戳参数 print(time.strptime(‘2014-11-11‘, ‘%Y-%m-%d‘)) print(time.strftime(‘%Y-%m-%d‘) )#默认当前时间 print(time.strftime(‘%Y-%m-%d‘,time.localtime())) #默认当前时间 print(time.asctime()) print(time.asctime(time.localtime())) print(time.ctime(time.time())) # 输出结果 1465723506.6008098 1465723506.0 time.struct_time(tm_year=2016, tm_mon=6, tm_mday=12, tm_hour=9, tm_min=25, tm_sec=6, tm_wday=6, tm_yday=164, tm_isdst=0) time.struct_time(tm_year=2016, tm_mon=6, tm_mday=12, tm_hour=17, tm_min=25, tm_sec=6, tm_wday=6, tm_yday=164, tm_isdst=0) time.struct_time(tm_year=2014, tm_mon=11, tm_mday=11, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=1, tm_yday=315, tm_isdst=-1) 2016-06-12 2016-06-12 Sun Jun 12 17:25:06 2016 Sun Jun 12 17:25:06 2016 Sun Jun 12 17:25:06 2016
import time
import datetime
print(time.clock()) #返回处理器时间,3.3开始已废弃
print(time.process_time()) #返回处理器时间,3.3开始已废弃
print(time.time()) #返回当前系统时间戳
print(time.ctime()) #输出Tue Jan 26 18:23:48 2016 ,当前系统时间
print(time.ctime(time.time()-86640)) #将时间戳转为字符串格式
print(time.gmtime(time.time()-86640)) #将时间戳转换成struct_time格式
print(time.localtime(time.time()-86640)) #将时间戳转换成struct_time格式,但返回 的本地时间
print(time.mktime(time.localtime())) #与time.localtime()功能相反,将struct_time格式转回成时间戳格式
#time.sleep(4) #sleep
print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将struct_time格式转成指定的字符串格式
print(time.strptime("2016-01-28","%Y-%m-%d") ) #将字符串格式转换成struct_time格式
常用:取时间
import datetime
‘‘‘
datetime.date:表示日期的类。常用的属性有year, month, day
datetime.time:表示时间的类。常用的属性有hour, minute, second, microsecond
datetime.datetime:表示日期时间
datetime.timedelta:表示时间间隔,即两个时间点之间的长度
timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]])
strftime("%Y-%m-%d")
‘‘‘
import datetime
print(datetime.datetime.now())
print(datetime.datetime.now() - datetime.timedelta(days=5))
# 输出结果
2016-06-12 17:25:06.637834
2016-06-07 17:25:06.637834
datetime module
import time
import datetime
print(datetime.date.today()) #输出格式 2016-01-26
print(datetime.date.fromtimestamp(time.time()-864400) ) #2016-01-16 将时间戳转成日期格式
current_time = datetime.datetime.now() #
print(current_time) #输出2016-01-26 19:04:30.335935
print(current_time.timetuple()) #返回struct_time格式
#datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]])
print(current_time.replace(2014,9,12)) #输出2014-09-12 19:06:24.074900,返回当前时间,但指定的值将被替换
str_to_date = datetime.datetime.strptime("21/11/06 16:30", "%d/%m/%y %H:%M") #将字符串转换成日期格式
new_date = datetime.datetime.now() + datetime.timedelta(days=10) #比现在加10天
new_date = datetime.datetime.now() + datetime.timedelta(days=-10) #比现在减10天
new_date = datetime.datetime.now() + datetime.timedelta(hours=-10) #比现在减10小时
new_date = datetime.datetime.now() + datetime.timedelta(seconds=120) #比现在+120s
print(new_date)
# 输出结果
2016-06-12
2016-06-02
2016-06-12 23:06:16.843536
time.struct_time(tm_year=2016, tm_mon=6, tm_mday=12, tm_hour=23, tm_min=6, tm_sec=16, tm_wday=6, tm_yday=164, tm_isdst=-1)
2014-09-12 23:06:16.843536
2016-06-12 23:08:16.871634
练习
import logging
#create logger
logger = logging.getLogger(‘TEST-LOG‘)
logger.setLevel(logging.DEBUG)
# create console handler and set level to debug
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
# create file handler and set level to warning
fh = logging.FileHandler("access.log")
fh.setLevel(logging.WARNING)
# create formatter
formatter = logging.Formatter(‘%(asctime)s - %(name)s - %(levelname)s - %(message)s‘)
# add formatter to ch and fh
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add ch and fh to logger
logger.addHandler(ch)
logger.addHandler(fh)
# ‘application‘ code
logger.debug(‘debug message‘)
logger.info(‘info message‘)
logger.warn(‘warn message‘)
logger.error(‘error message‘)
logger.critical(‘critical message‘)
# 输出结果
2016-06-12 22:44:18,521 - TEST-LOG - DEBUG - debug message
2016-06-12 22:44:18,521 - TEST-LOG - INFO - info message
2016-06-12 22:44:18,521 - TEST-LOG - WARNING - warn message
2016-06-12 22:44:18,522 - TEST-LOG - ERROR - error message
2016-06-12 22:44:18,522 - TEST-LOG - CRITICAL - critical message
标签:
原文地址:http://www.cnblogs.com/liangdalong/p/5579138.html