python成长之路15——json pickle time log

一. 序列化模块——json和pickle

      序列化:  将python的数据类型序列化成字符串或者bytes类型

  反序列化:将字符串或者bytes类型反序列化成python的数据类型

      注意:在python里单引号和双引号是没有区别的,但是在别的语言里,单引号是用来引字符的,双引号是用来引字符串的。所以如果我们的字符串写成这样:"['alex','aric']"要和别的语言做交互的时候是有问题的。所以我们要保证必须:外面是单引号,里面是双引号

 1 import json
 2 
 3 li1=["alex","aric","jack"]
 4 s1=json.dumps(li1)
 5 print(s1,type(s1))
 6 
 7 s2='{"k1":"v1","k2":"v2"}'
 8 dic=json.loads(s2)
 9 print(dic,type(dic))
10 
11 执行结果:
12 ["alex", "aric", "jack"] <class 'str'>
13 {'k2': 'v2', 'k1': 'v1'} <class 'dict'>
json loads和dumps
 1 import json
 2 
 3 li1=["alex","aric","jack","你好"]
 4 json.dump(li1,open("db","w",encoding="utf8"))
 5 
 6 ret=json.load(open("db","r+",encoding="utf8"))
 7 print(ret,type(ret))
 8 #dump和load不仅可以序列化,还可以实现写入文件和从文件读出
 9 
10 执行结果:
11 ['alex', 'aric', 'jack', '你好'] <class 'list'>
json dump和load
 1 import pickle
 2 li1=["alex","aric",123]
 3 ret=pickle.dumps(li1)
 4 print(ret,type(ret))
 5 #pickle序列化成的是bytes类型
 6 
 7 li2=pickle.loads(ret)
 8 print(li2,type(li2))
 9 
10 执行结果:
11 b'\x80\x03]q\x00(X\x04\x00\x00\x00alexq\x01X\x04\x00\x00\x00aricq\x02K{e.' <class 'bytes'>
12 ['alex', 'aric', 123] <class 'list'>
pickle dumps和loads
1 import pickle
2 dic={"k1":"v1","k2":"v2","k3":"你好"}
3 pickle.dump(dic,open("db","wb"))
4 #因为pickle要序列化成bytes类型,所以写入和读出的时候必须加"b"
5 
6 ret=pickle.load(open("db","rb"))
7 print(ret)
pickle dump和load

json和pickle的区别:

(1) json可以跨语言跨平台使用;

     json只能处理基本的数据类型:dict,list,tuple,str,int,float,True,False,None

(2) pickle只能在python里使用,而且对python的版本可能有要求,py2里pickle序列化的数据可能py3打不开;

     pickle支持任何数据类型,例如:玩儿游戏的时候,我们要存档(复杂的数据类型),就只能用pickle啦;

二. 时间模块time&datetime    

 1 #_*_coding:utf-8_*_
 2 __author__ = 'Alex Li'
 3 
 4 import time
 5 # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
 6 # print(time.altzone)  #返回与utc时间的时间差,以秒计算\
 7 # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
 8 # print(time.localtime()) #返回本地时间 的struct time对象格式
 9 # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
10 
11 # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
12 #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
13 
14 # 日期字符串 转成  时间戳
15 # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
16 # print(string_2_struct)
17 # #
18 # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
19 # print(struct_2_stamp)
20 
21 #将时间戳转为字符串格式
22 # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
23 # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
24 
25 #时间加减
26 import datetime
27 
28 # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
29 #print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
30 # print(datetime.datetime.now() )
31 # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
32 # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
33 # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
34 # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
35 
36 #
37 # c_time  = datetime.datetime.now()
38 # print(c_time.replace(minute=3,hour=2)) #时间替换
time&datetime
DirectiveMeaningNotes
%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.  
%d Day of the month as a decimal number [01,31].  
%H Hour (24-hour clock) as a decimal number [00,23].  
%I Hour (12-hour clock) as a decimal number [01,12].  
%j Day of the year as a decimal number [001,366].  
%m Month as a decimal number [01,12].  
%M Minute as a decimal number [00,59].  
%p Locale’s equivalent of either AM or PM. (1)
%S Second as a decimal number [00,61]. (2)
%U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. (3)
%w Weekday as a decimal number [0(Sunday),6].  
%W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. (3)
%x Locale’s appropriate date representation.  
%X Locale’s appropriate time representation.  
%y Year without century as a decimal number [00,99].  
%Y Year with century as a decimal number.  
%z Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59].  
%Z Time zone name (no characters if no time zone exists).  
%% A literal '%' character.

 

三. 日志模块

python的logging模块提供了标准的日志接口,可以通过它存储各种格式的日志,logging的日志可以分为debug,info,warning,error,critical5个级别(level),默认的level为warning。

 1 import logging
 2 
 3 logging.debug("debug")
 4 logging.info("info")
 5 logging.warning("warning")
 6 logging.error("error")
 7 logging.critical("critical")
 8 
 9 执行结果:
10 WARNING:root:warning
11 ERROR:root:error
12 CRITICAL:root:critical
13 
14 import logging
15 
16 #输出level对应的日志级别
17 print(logging._levelToName)
18 #basicConfig对logging进行一些设置
19 logging.basicConfig(filename='log.log',  #设置输出到文件,默认输出到console
20                     format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s', #设置日志输出格式
21                     datefmt='%Y-%m-%d %H:%M:%S %p', #设置时间格式
22                     level=0, #设置日志级别,0为不设置,则级别为debug
23                     )
24 
25 logging.debug("debug")
26 logging.info("info")
27 logging.warning("warning")
28 logging.error("error")
29 logging.critical("critical")
30 
31 执行结果:
32 终端:
33 {0: 'NOTSET', 50: 'CRITICAL', 20: 'INFO', 40: 'ERROR', 10: 'DEBUG', 30: 'WARNING'}
34 文件log.log:
35 2017-03-03 17:56:09 PM - root - DEBUG -func:  debug
36 2017-03-03 17:56:09 PM - root - INFO -func:  info
37 2017-03-03 17:56:09 PM - root - WARNING -func:  warning
38 2017-03-03 17:56:09 PM - root - ERROR -func:  error
39 2017-03-03 17:56:09 PM - root - CRITICAL -func:  critical
logging
还可以这样写:logging.log(30,'log')  #30为level,
执行结果为: WARNING:root:log

日志输出格式:

posted @ 2017-02-28 17:05  meitangyanyan  阅读(183)  评论(0编辑  收藏  举报