規範化格式目錄 `time模塊 datatime` random模塊` collection

day18

一丶規範化格式化目錄

六個目錄:

#### 對某某項目進行一個標準化的開發,進行規範化.
#bin   : 啓動項目程序的主入口

#conf : 項目的配置文件

#core : 主要邏輯(業務邏輯)

#db   : 存放數據()

#lib   : 輔助文件(存放公共的一些方法)


#README : 項目文檔說明

 

二丶time模塊(時間模塊)

時間的三種方式:

1.時間戳 ,用於計時 (始於1970年,Unix的誕生.)app

2.格式化時間 , dom

3.元組結構化時間, 元組則是用來操做時間的.(做爲一種中間介質,用於轉換)函數

### 1.時間戳   ,從1970年到如今的一個時間戳,秒爲單位
   print(time.time())

### 2.格式化時間
   # 字符串類型 ,參數 :%Y-%m-%d %H:%M:%S ,不能包含Unicode的編碼
   print(time.strftime('%Y-%m-%d %H:%M:%S'))

   #不能包含Unicode的編碼
   print(time.strftime('%Y{}%m{}%d{} %H:%M:%S').format('年','月','日'))

### 3.結構化時間
   print(time.localtime())


### 時間轉換
# 時間戳轉換成結構化時間
   ret=time.time()         # 時間戳
   st_time=time.localtime(ret) # 時間戳轉換成 結構化時間
   print(st_time)
   
# 結構化時間轉換成格式化時間
   ft=time.strftime('%Y-%m-%d',st_time)  # 將結構化時間轉換成格式化時間
   print(ft)

# 格式化時間轉換成結構化時間,
   ft=time.strftime('%Y-%m-%d %H:%M:%S')   # 格式化時間.
   st=time.strptime(ft,'%Y-%m-%d %H:%M:%S')  # 格式化時間轉換成 結構化時間,
   print(st)
   
# 結構化時間轉換成時間戳,
   timestamp=time.mktime(st)  # 結構化時間轉換成時間戳
   print(timestamp)

時間轉換以下圖👇:

 

時間測試題:

## 突發奇想: 算一算 從1970到2019-06-28如今一共同多少天
   count=0
   for i in range(1970,2019):          
       ret=time.strptime(f'{i}-12-31','%Y-%m-%d')
       count+=int(ret.tm_yday)
   res=time.strptime('2019-06-28','%Y-%m-%d')
   print(res)
   print(res.tm_yday+count)
 

## 用戶輸入一個格式化的時間如:2019-06-28,給返回這一天在這一年中是第幾天
   def user_time(times_us):
       ret = time.strptime(times_us,'%Y-%m-%d')
       return ret.tm_yday
   print(user_time(input('請輸入年-月-日:>>').strip()))

   
   
   
## 計算博客園園齡
   # 將指定時間轉換成時間戳
   bok_time='2019-05-20 00:00:00'
   #先轉換成結構化時間,在由結構化時間轉換成時間戳
   t2=time.mktime(time.strptime(bok_time,'%Y-%m-%d %H:%M:%S'))

   create_time=now_time-t2   # 得到一個時間戳.當前時間戳 - 建立時的時間戳

   # gmtime(sec) 計算 從1970時間 到如今已通過了多少時間函數將一個時間戳轉換爲UTC時區(0時區)的struct_time,可選的參數sec表示從1970-1-1以來的秒數。(返回結構tm 表明目前UTC 時間。)
   
   # localtime() 是格式本地當前時間,(會把差值+時區一塊兒算)(返回結構tm 表明目前的當地時間)
   
   time_struct=time.gmtime(create_time)
   print(f'如今已通過去了{time_struct.tm_year-1970}年,{time_struct.tm_mon-1}月,{time_struct.tm_mday-1}天,{time_struct.tm_hour}小時,{time_struct.tm_min}分,{time_struct.tm_sec}秒,夏令時:{time_struct.tm_isdst}')

 

三丶datatime模塊(時間模塊)

import datetime

### 如今的時間
now_datetime=datetime.datetime.now()
print(now_datetime)  # 2019-06-28 15:29:38.478080



### 在當前時間上,爲其增減時間(時,分,秒,天,周)
now_time=datetime.datetime.now()
# 如今的時間加上增刪的時間
print(now_time+datetime.timedelta(weeks=3))  # 三週後
print(now_time+datetime.timedelta(weeks=-3)) # 三週前



### 指定調整 年月日時分秒等
now_time2=datetime.datetime.now()
print(now_time2.replace(year=1949))  # 指定年
print(now_time2.replace(year=1997,month=11,day=16,hour=12,minute=0,second=0))  # 指定年 , 月, 日



### 將時間戳轉換成格式化時間
print(datetime.date.fromtimestamp(3125456312))

 

四丶random模塊(生成隨機數)


import  random

# 得到一個 大於0,且小於1 ,隨機小數
print(random.random())

# 1到7之間, 隨機小數
print(random.uniform(1,7))


# 隨機整數     顧頭也顧尾
print(random.randint(1,5))


# 隨機切片 顧頭不顧尾
print(random.randrange(1,10,2))



# 隨機選擇一個返回
print(random.choice([1,'22',3,4]))


# 隨機選擇多個
print(random.sample([1,2,3,4,5,6,7]))



# 打亂列表次序
item=[i for i  in range(10)]
random.shuffle(item)  # 對原列表 打亂順序
print(item)

 

 

五丶collection模塊

額外的Counter,deque,defaultdict,namedtuple,OrderedDict數據類型


### 內置數據類型 (dict, list,set ,tuple) 基礎上: Counter,deque,defaultdict,namedtuple和OrderedDict等

# 1.namedtuple: 生成能夠使用名字來訪問元素內容的tuple 元組
   from collections import namedtuple
   # 表示一個二維座標點
   Point=namedtuple('Point',['X','Y'])
   p=Point(1,2)
   print(p.X,p.Y)

   #座標和半徑表示一個圓
   Circle = namedtuple('Circle', ['x', 'y', 'r'])
   c=Circle(1,2,3)


### 2.deque: 雙端隊列,能夠快速的從另一側追加和推出對象 ,
   # list 插入和刪除元素慢,是線性存儲,數據量大的時候,插入和刪除效率很低。
   #了高效實現插入和刪除操做的雙向列表,適合用於隊列和棧:
   from collections import  deque
   q=deque(['a','b','c'])
   q.append('x')  # 末尾插入
   q.appendleft('y') # 列頭插入
   print(q.pop())   # 默認刪除末尾元素,並返回刪除元素
   print(q.popleft()) # 默認刪除頭元素
   print(q)


### 3.Counter: 計數器,主要用來計數   ###很吊!!!!
   # 它是一個無序的容器類型,以字典的鍵值對形式存儲,其中元素做爲key,其計數做爲value。
   # 計數值能夠是任意的Interger(包括0和負數)。
   # Counter類和其餘語言的bags或multisets很類似。
   import random
   from collections import Counter
   c=Counter('nopqrsydefgst')
   print(c)
   
   num_li=[random.randint(1,20) for  i in range(20)]
   c2=Counter(num_li)
   print(c2)


# 4.OrderedDict: 有序字典
   from collections import OrderedDict
   d=dict([('e', 2), ('b', 2), ('c', 3)]) # 字典推導式 將可迭代對象默認循環獲得一個元組,
   print(d)
   od = OrderedDict([('e', 1), ('b', 2), ('c', 3)])
   print(od)
   od['z'] = 1  # 添加元素 只會往末尾添加
   od['x'] = 2  #
   od['y'] = 3  #
   print(od,type(od))
   print(od.keys())



### 5.defaultdict: 帶有默認值的字典
   # 放置數據類型做爲字典的值類型
       from collections import defaultdict
       values = [11, 22, 33,44,55,66,77,88,99,90]
       my_dict = defaultdict(list)
       for value in  values:
           if value>66:
               my_dict['k1'].append(value)
           else:
               my_dict['k2'].append(value)
       print(my_dict)


   # 當鍵不存在 執行lambda 函數
   from collections import  defaultdict
   dd=defaultdict(lambda :'N/A')
   dd['key1']='abc'
   print(dd)
   print(dd['key1'])
   print(dd['key2']) # key2不存在,返回默認值 'N/A'
相關文章
相關標籤/搜索