分享

Python-25-内置模块

 印度阿三17 2019-08-10
  1. time

    1. 获取当前的时间戳(单位:秒)

       import time
       print(time.time())
      
    2. 延时(1秒输出1个数字)

       import time
       def delay():
           for i in range(3):
               print(i)
               time.sleep(1)
       delay()
      
  2. datetime

    时间有三种格式:datetime、时间戳、字符串

    1. 获取当前时间

       from datetime import datetime
       time_now=datetime.now()
       print(time_now)  # 2019-07-31 14:00:21.196772
       #时间类型的方法
       print(time_now.year)
       print(time_now.month)
       print(time_now.day)
       print(time_now.hour)
       print(time_now.minute)
       print(time_now.second)
       print(time_now.date()) # 2019-07-31
      
    2. 时间类型(datetime)<==>字符串类型

       from datetime import datetime
       time_now = datetime.now()
       # 时间类型(datetime)==>字符串类型:datetime.strftime()
       time_now_str_date = time_now.strftime('%Y-%m-%d')
       print(time_now_str_date)  # 2019-07-31
       time_now_str_time = time_now.strftime('%H:%M:%S')
       print(time_now_str_time)  # 13:47:47
       # 字符串类型==>时间类型(datetime):datetime.strptime()
       str = '1998-3-15'
       str_date = datetime.strptime(str,'%Y-%m-%d')
       print(str_date)  # 1998-03-15 00:00:00
      
    3. 时间类型(datetime)<==>时间戳类型(time)

       import time
       from datetime import datetime
       # 时间类型(datetime)==>时间戳类型(time):time.mktime(datetime.timetuple())
       time_now=datetime.now()
       time_now_stamp = time.mktime(time_now.timetuple())
       time_past_stamp = time.mktime(datetime.strptime('1998-3-15','%Y-%m-%d').timetuple())
       print((time_now_stamp - time_past_stamp) // (60 * 60 * 24 * 365))  # 21
       # 时间戳类型(time)==>时间类型(datetime):datetime.fromtimestamp()
       stamp_to_time = datetime.fromtimestamp(time_now_stamp)
       print(stamp_to_time)  # 2019-07-31 14:52:02
      
    4. 世界标准时间

       import time
       from datetime import datetime,timedelta
       time_now=datetime.utcnow()
       print(time_now)  # 2019-07-31 07:02:38.144018
       #在国际标准时间上的时延
       end_time=time_now timedelta(days=3)
       print(end_time)  # 2019-08-03 07:03:28.801905
      
    5. 格式参数

      %Y 带世纪部分的十制年份

      %m 十进制表示的月份

      %d 十进制表示的每月的第几天

      %H 24小时制的小时

      %M 十时制表示的分钟数

      %S 十进制的秒数

      %c 标准时间,如:04/25/17 14:35:14 类似于这种形式

  3. json(看课件)

  4. collections

    collections模块在这些Python内置数据类型的基础上,提供了几个额外的数据类型

    • namedtuple(): 生成可以使用名字来访问元素内容的tuple子类
    • deque: 双端队列,可以快速的从另外一侧追加和推出对象
    • Counter: 计数器,主要用来计数
    • OrderedDict: 有序字典
    • defaultdict: 带有默认值的字典
    1. namedtuple()

      namedtuple主要用来产生可以使用名称来访问元素的数据对象,通常用来增强代码的可读性, 在访问一些tuple类型的数据时尤其好用。

       from collections import namedtuple
      
       websites = [
           ('Sohu', 'http://www.google.com/', u'张朝阳'),
           ('Sina', 'http://www.sina.com.cn/', u'王志东'),
           ('163', 'http://www.163.com/', u'丁磊')
       ]
       
       Website = namedtuple('Website', ['name', 'url', 'founder'])
       
       for website in websites:
           website = Website._make(website)
           print website
      
    2. deque

      deque其实是 double-ended queue 的缩写,翻译过来就是双端队列,它最大的好处就是实现了从队列 头部快速增加和取出对象: .popleft(), .appendleft() 。

      你可能会说,原生的list也可以从头部添加和取出对象啊?就像这样:

      l.insert(0, v)
      l.pop(0)
      但是值得注意的是,list对象的这两种用法的时间复杂度是 O(n) ,也就是说随着元素数量的增加耗时呈 线性上升。而使用deque对象则是 O(1) 的复杂度,所以当你的代码有这样的需求的时候, 一定要记得使用deque。

      作为一个双端队列,deque还提供了一些其他的好用方法,比如 rotate 等。

    3. Counter

      计数器是一个非常常用的功能需求,collections也贴心的为你提供了这个功能。

       from collections import Counter
      
       s = '''A Counter is a dict subclass for counting hashable objects. It is an unordered collection where elements are stored as dictionary keys and their counts are stored as dictionary values. Counts are allowed to be any integer value including zero or negative counts. The Counter class is similar to bags or multisets in other languages.'''.lower()
       
       c = Counter(s)
       # 获取出现频率最高的5个字符
       print c.most_common(5)
      
    4. OrderedDict

      在Python中,dict这个数据结构由于hash的特性,是无序的,这在有的时候会给我们带来一些麻烦, 幸运的是,collections模块为我们提供了OrderedDict,当你要获得一个有序的字典对象时,用它就对了。

       from collections import OrderedDict
      
       items = (
           ('A', 1),
           ('B', 2),
           ('C', 3)
       )
       
       regular_dict = dict(items)
       ordered_dict = OrderedDict(items)
       
       print 'Regular Dict:'
       for k, v in regular_dict.items():
           print k, v
       
       print 'Ordered Dict:'
       for k, v in ordered_dict.items():
           print k, v
      
    5. more

      https://docs./3.7/library/collections.html#userdict-objects

来源:https://www./content-1-385851.html

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多