經常使用模塊學習(二)

                                 經常使用模塊學習(二)

  • 經常使用模塊學習—包及跨模塊導入

    • 當你的模塊文件愈來愈多,就須要對模塊文件進行劃分,好比把負責跟數據庫交互的都放一個文件夾,把與頁面交互相關的放一個文件夾
      .
      └── my_proj
          ├── crm #代碼目錄
          │   ├── admin.py
          │   ├── apps.py
          │   ├── models.py
          │   ├── tests.py
          │   └── views.py
          ├── manage.py
          └── my_proj #配置文件目錄
              ├── settings.py
              ├── urls.py
              └── wsgi.py

      一個文件夾管理多個模塊文件,這個文件夾就被稱爲包

    • 那不一樣包之間的模塊怎樣互相導入呢?
      crm/views.py內容:
      def sayhi():
          print('hello world!')
      
      經過manage.py調用:
      from crm import views
      
      views.sayhi()

      用 python2 執行 manage.py:
      
      Alexs-MacBook-Pro:my_proj alex$ ls
      crm        manage.py    my_proj
      Alexs-MacBook-Pro:my_proj alex$ python manage.py 
      Traceback (most recent call last):
        File "manage.py", line 6, in <module>
          from crm import views
      ImportError: No module named crm      找不到模塊

      包就是文件夾,但該文件夾下必須存在 __init__.py 文件, 該文件的內容能夠爲空。__int__.py用於標識當前文件夾是一個包。

    • 在crm目錄下建立一個空文件__int__.py ,再執行一次
      Alexs-MacBook-Pro:my_proj alex$ touch crm/__init__.py #建立一個空文件
      Alexs-MacBook-Pro:my_proj alex$ 
      Alexs-MacBook-Pro:my_proj alex$ ls crm/
      __init__.py    admin.py    models.py    views.py
      __pycache__    apps.py        tests.py    views.pyc
      Alexs-MacBook-Pro:my_proj alex$ python manage.py 
      hello world!
      
      注意:在python3裏,即便目錄下沒__int__.py文件也能建立成功,應該是解釋器優化所致,可是建立包的時候仍是要記得加上這個文件。
    • 例:
    • settings.py:
      DATABASES= {
          'host':'localhost'
      }
      print('in proj/settings.py')
      
      
      views.py:
      from proj import settings
      
      def sayhi():
          print('hello world!')
      
      
      manage.py:
      from crm import views
      
      views.sayhi()
      
      執行 manage.py

  • 經常使用模塊學習—跨模塊導入2

     1 import sys,os
     2 
     3 #sys.path.append("E:/Python/work/myFirstPro/第4章/packages/my_proj/")
     4 #print(sys.path)
     5 #from proj import settings
     6 
     7 print(dir())                   #結果爲:['__annotations__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', 'os', 'sys']
     8 print(__file__)                #結果爲:E:/Python/work/myFirstPro/第4章/packages/my_proj/crm/views.py
     9 
    10 #絕對路徑
    11 DASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))       #abspath 絕對路徑
    12 sys.path.append(DASE_DIR)
    13 from proj import settings
    14 
    15 #相對路徑
    16 # DASE_DIR = os.path.dirname(os.path.dirname(__file__))        #os.path.dirname(__file__)   使目錄往上走一層
    17 # print(DASE_DIR)                               #結果爲:E:/Python/work/myFirstPro/第4章/packages/my_proj
    18 # sys.path.append(DASE_DIR)
    19 # from proj import settings                    #結果爲:in proj/settings.py
    20 
    21 def sayhi():
    22     print('hello world!')
  • 經常使用模塊學習—相對導入

    絕對導入&相對導入
    在linux裏能夠經過cd ..回到上一層目錄 ,cd ../.. 往上回2層,這個..就是指相對路徑,在python裏,導入也能夠經過..
    
    例如:
    .
    ├── __init__.py
    ├── crm
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   ├── tests.py
    │   ├── views.py  #from ..proj import settings 
    ├── manage.py   
    └── proj
        ├── __init__.py
        ├── settings.py #from .import urls  
        ├── urls.py
        └── wsgi.py
    
    views.py裏代碼:
    from ..proj import settings
    def sayhi():
        print('hello world!')
    
    print(settings.DATABASES)
    
    執行結果報錯了:
    Traceback (most recent call last):
    File "my_proj/crm/views.py", line 4, in <module>
     from ..proj import settings
    SystemError: Parent module '' not loaded, cannot perform relative import
    
    或者有人會看到這個錯
    ValueError: attempted relative import beyond top-level package
    
    
    其實這兩個錯誤的緣由歸根結底是同樣的:在涉及到相對導入時,package所對應的文件夾必須正確的被python解釋器視做package,而不是普通文件夾。不然因爲不被視做package,沒法利用package之間的嵌套關係實現python中包的相對導入。
    
    
    文件夾被python解釋器視做package須要知足兩個條件:
    1、文件夾中必須有__init__.py文件,該文件能夠爲空,但必須存在該文件。
    2、不能做爲頂層模塊來執行該文件夾中的py文件(即不能做爲主函數的入口)。
    
    
    解決辦法就是,既然你在views.py裏執行了相對導入,那就不要把views.py看成入口程序,能夠經過上一級的manage.py調用views.py
    
    .
    ├── __init__.py
    ├── crm
    │   ├── __init__.py
    │   ├── admin.py
    │   ├── apps.py
    │   ├── models.py
    │   ├── tests.py
    │   ├── views.py  #from ..proj import settings 
    ├── manage.py  #from crm import views 
    └── proj
        ├── __init__.py
        ├── settings.py #from .import urls  
        ├── urls.py
        └── wsgi.py
    
    事實證實仍是不行,報錯:
    ValueError: attempted relative import beyond top-level package
    
    
    但把from ..proj import settings 改爲from . import models 後卻執行成功了,爲何呢?
    
    from .. import models會報錯的緣由是,這句代碼會把manage.py所在的這一層視做package,但實際上它不是,由於package不能是頂層入口代碼,若想不出錯,只能把manage.py往上再移一層。
    
    正確的代碼目錄結構以下:
     packages/
        ├── __init__.py
        ├── manage.py #from my_proj.crm  import views
        └── my_proj
            ├── crm
            │   ├── admin.py
            │   ├── apps.py
            │   ├── models.py
            │   ├── tests.py
            │   ├── views.py  #from . import models;  from ..proj import settings 
            └── proj
                ├── __init__.py
                ├── settings.py
                ├── urls.py
                └── wsgi.py
    
    再執行manage.py就不會報錯了。
    
    注意:雖然python支持相對導入,但對模塊間的路徑關係要求比較嚴格,處理不當就容易出錯,so並不建議在項目裏常用。
  • 經常使用模塊學習—time 模塊詳解

在日常的代碼中,咱們經常須要與時間打交道。在Python中,與時間處理有關的模塊就包括:time,datetime,calendarpython

    • 在Python中,一般有這幾種方式來表示時間:
      • 時間戳
      • 格式化的時間字符串
      • 元組(struct_time)共九個元素。因爲Python的time模塊實現主要調用C庫,因此各個平臺可能有所不一樣。
    • 幾個定義
      • UTC(Coordinated Universal Time,世界協調時)亦即格林威治天文時間,世界標準時間。在中國爲UTC+8。DST(Daylight Saving Time)即夏令時。
      • 時間戳(timestamp)的方式:一般來講,時間戳表示的是從1970年1月1日00:00:00開始按秒計算的偏移量。咱們運行「type(time.time())」,返回的是float類型。
      • 元組(struct_time)方式:struct_time元組共有9個元素,返回struct_time的函數主要有gmtime(),localtime(),strptime()。下面列出這種方式元組中的幾個元素:
        索引(Index)    屬性(Attribute)    值(Values)
        0     tm_year(年)                 好比2011 
        1     tm_mon(月)                  1 - 12
        2     tm_mday(日)                 1 - 31
        3     tm_hour(時)                 0 - 23
        4     tm_min(分)                  0 - 59
        5     tm_sec(秒)                  0 - 61
        6     tm_wday(weekday)            0 - 6(0表示週日)
        7     tm_yday(一年中的第幾天)       1 - 366
        8     tm_isdst(是不是夏令時)            默認爲-1
    • time模塊的方法

      • time.localtime([secs]):將一個時間戳轉換爲當前時區的struct_time。secs參數未提供,則以當前時間爲準。
      • time.gmtime([secs]):和localtime()方法相似,gmtime()方法是將一個時間戳轉換爲UTC時區(0時區)的struct_time。
      • time.time():返回當前時間的時間戳。
      • time.mktime(t):將一個struct_time轉化爲時間戳。
      • time.sleep(secs):線程推遲指定的時間運行。單位爲秒。
      • time.asctime([t]):把一個表示時間的元組或者struct_time表示爲這種形式:'Sun Oct 1 12:04:38 2017'。若是沒有參數,將會將time.localtime()做爲參數傳入。
      • time.ctime([secs]):把一個時間戳(按秒計算的浮點數)轉化爲time.asctime()的形式。若是參數未給或者爲None的時候,將會默認time.time()爲參數。它的做用至關於time.asctime(time.localtime(secs))。
      • time.strftime(format[, t]):把一個表明時間的元組或者struct_time(如由time.localtime()和time.gmtime()返回)轉化爲格式化的時間字符串。若是t未指定,將傳入time.localtime()。linux

        • 舉例:time.strftime("%Y-%m-%d %X", time.localtime()) #輸出'2017-10-01 12:14:23'
      • time.strptime(string[, format]):把一個格式化時間字符串轉化爲struct_time。實際上它和strftime()是逆操做。git

        • 舉例:time.strptime('2017-10-3 17:54',"%Y-%m-%d %H:%M") #輸出 time.struct_time(tm_year=2017, tm_mon=10, tm_mday=3, tm_hour=17, tm_min=54, tm_sec=0, tm_wday=1, tm_yday=276, tm_isdst=-1)

 

    • 字符串轉時間格式對應表

       1 %a            Locale’s abbreviated weekday name.    
       2 %A            Locale’s full weekday name.    
       3 %b            Locale’s abbreviated month name.    
       4 %B            Locale’s full month name.    
       5 %c            Locale’s appropriate date and time representation.    
       6 %d            Day of the month as a decimal number [01,31].    
       7 %H            Hour (24-hour clock) as a decimal number [00,23].    
       8 %I            Hour (12-hour clock) as a decimal number [01,12].    
       9 %j            Day of the year as a decimal number [001,366].    
      10 %m            Month as a decimal number [01,12].    
      11 %M            Minute as a decimal number [00,59].    
      12 %p            Locale’s equivalent of either AM or PM.    (1)
      13 %S            Second as a decimal number [00,61].    (2)
      14 %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)
      15 %w            Weekday as a decimal number [0(Sunday),6].    
      16 %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)
      17 %x            Locale’s appropriate date representation.    
      18 %X            Locale’s appropriate time representation.    
      19 %y            Year without century as a decimal number [00,99].    
      20 %Y            Year with century as a decimal number.    
      21 %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].    
      22 %Z            Time zone name (no characters if no time zone exists).    
      23      %%    A literal '%' character.

 

 

import time

#返回當前時間的時間戳
time.time()
#結果爲:1537339625.2724273
time.time()
#結果爲:1537339629.5167184
time.time()
#結果爲:1537339633.3674865
time.time()
#結果爲:1537339650.316459
time.time()
#結果爲:1537339651.5483134
time.time()
#結果爲:1537339652.9071617
time.time()
#結果爲:1537339654.12688
time.time() / 3600 /24 /365
#結果爲:48.74872318235897


#將一個時間戳轉換爲當前時區的struct_time
time.localtime()
#結果爲:time.struct_time(tm_year=2018, tm_mon=9, tm_mday=19, tm_hour=14, tm_min=50, tm_sec=32, tm_wday=2, tm_yday=262, tm_isdst=0)
time.localtime()
#結果爲:time.struct_time(tm_year=2018, tm_mon=9, tm_mday=19, tm_hour=14, tm_min=50, tm_sec=39, tm_wday=2, tm_yday=262, tm_isdst=0)
a = time.localtime()
a.tm_year
#結果爲:2018
'%s-%s-%s'%(a.tm_year,a.tm_mon,a.tm_mday)
#結果爲:'2018-9-19'


#和localtime()方法相似,將一個時間戳轉換爲UTC時區(0時區)的struct_time
time.gmtime()
#結果爲:time.struct_time(tm_year=2018, tm_mon=9, tm_mday=19, tm_hour=7, tm_min=6, tm_sec=12, tm_wday=2, tm_yday=262, tm_isdst=0)
a=time.localtime(1403232424)
a
#結果爲:time.struct_time(tm_year=2014, tm_mon=6, tm_mday=20, tm_hour=10, tm_min=47, tm_sec=4, tm_wday=4, tm_yday=171, tm_isdst=0)
a=time.localtime(140323242)
a
#結果爲:time.struct_time(tm_year=1974, tm_mon=6, tm_mday=13, tm_hour=10, tm_min=40, tm_sec=42, tm_wday=3, tm_yday=164, tm_isdst=0)


#將一個struct_time轉化爲時間戳
time.mktime(a)
#結果爲:140323242.0


#線程推遲指定的時間運行。單位爲秒
time.sleep(2)


#把一個表示時間的元組或者struct_time表示爲這種形式:'Sun Oct 1 12:04:38 2017'。若是沒有參數,將會將time.localtime()做爲參數傳入。
time.asctime()
#結果爲:'Wed Sep 19 18:12:52 2018'


#把一個時間戳(按秒計算的浮點數)轉化爲time.asctime()的形式
time.ctime()
#結果爲:'Wed Sep 19 18:13:21 2018'
time.ctime(123232)
#結果爲:'Fri Jan  2 18:13:52 1970'
time.ctime(0)
#結果爲:'Thu Jan  1 08:00:00 1970'


#把一個表明時間的元組或者struct_time 轉化爲格式化的時間字符串。
time.strftime('%Y-%m-%d')
#結果爲'2018-09-19'
time.strftime('%Y-%m-%d %H:%M:%S',)
#結果爲'2018-09-19 18:19:16'
time.strftime('%Y-%m-%d %H:%M:%S',a)
#結果爲'1974-06-13 13:40:42'
time.strftime('%Y-%m-%d %H:%M:%S %a',a)
#結果爲'1974-06-13 13:40:42 Thu'
time.strftime('%Y-%m-%d %H:%M:%S %A',a)
#結果爲'1974-06-13 13:40:42 Thursday'
time.strftime('%Y-%m-%d %H:%M:%S %p',a)
#結果爲'1974-06-13 13:40:42 AM'
time.strftime('%Y-%m-%d %H:%M:%S %U')
#結果爲'2018-09-19 18:20:36 37'
time.strftime('%Y-%m-%d %H:%M:%S %w')
#結果爲'2018-09-19 18:21:02 3'
time.strftime('%y-%m-%d %H:%M:%S %w')
#結果爲'18-09-19 18:21:29 3'
time.strftime('%y-%m-%d %H:%M:%S %z')
#結果爲'18-09-19 18:21:41 +0800'
time.strftime('%y-%m-%d %H:%M:%S %Z')
#結果爲'18-09-19 18:21:45 ?D1¨²¡À¨º¡Á?¨º¡À??'


#把一個格式化時間字符串轉化爲struct_time,實際上它和strftime()是逆操做。
s=time.strftime('%Y %m-%d %H:%M:%S')
s
#結果爲'2018 09-19 18:26:23'
time.strptime(s,'%Y %m-%d %H:%M:%S')
#結果爲time.struct_time(tm_year=2018, tm_mon=9, tm_mday=19, tm_hour=18, tm_min=26, tm_sec=23, tm_wday=2, tm_yday=262, tm_isdst=-1)
s2 = time.strptime(s,'%Y %m-%d %H:%M:%S')
time.mktime(s2)
#結果爲1537341983.0

 

  • 經常使用模塊學習—tatetime 模塊詳解

 

相比於time模塊,datetime模塊的接口則更直觀、更容易調用。

datetime模塊定義了下面這幾個類:數據庫

  • datetime.date:表示日期的類。經常使用的屬性有year, month, day;
  • datetime.time:表示時間的類。經常使用的屬性有hour, minute, second, microsecond;
  • datetime.datetime:表示日期時間。
  • datetime.timedelta:表示時間間隔,即兩個時間點之間的長度。
  • datetime.tzinfo:與時區有關的相關信息。(這裏不詳細充分討論該類,感興趣的童鞋能夠參考python手冊)

 

咱們須要記住的方法僅如下幾個:app

  •  d=datetime.datetime.now() 返回當前的datetime日期類型
d.timestamp(),d.today(), d.year,d.timetuple()等方法能夠調用
  • datetime.date.fromtimestamp(322222) 把一個時間戳轉爲datetime日期類型

 

  • 時間運算
>>> datetime.datetime.now()

datetime.datetime(2017, 10, 1, 12, 53, 11, 821218)

>>> datetime.datetime.now() + datetime.timedelta(4) #當前時間 +4天

datetime.datetime(2017, 10, 5, 12, 53, 35, 276589)

>>> datetime.datetime.now() + datetime.timedelta(hours=4) #當前時間+4小時

datetime.datetime(2017, 10, 1, 16, 53, 42, 876275)
  • 時間替換
>>> d.replace(year=2999,month=11,day=30)

datetime.date(2999, 11, 30)

 

import datetime
import time
datetime.datetime.now()
#結果爲:datetime.datetime(2018, 9, 19, 19, 9, 38, 72617)
a=datetime.datetime.now()
a.year
#結果爲:2018
a.month
#結果爲:9
a
#結果爲:datetime.datetime(2018, 9, 19, 19, 10, 30, 236846)
time.time()
#結果爲:1537344708.7243214
datetime.date.fromtimestamp(time.time())
#結果爲:datetime.date(2018, 9, 19)
d2 = datetime.date.fromtimestamp(time.time())
d2.year
#結果爲:2018
d2.timetuple()
#結果爲:time.struct_time(tm_year=2018, tm_mon=9, tm_mday=19, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=262, tm_isdst=-1)


#時間運算
datetime.timedelta(1)
#結果爲:datetime.timedelta(days=1)
datetime.datetime.now()
#結果爲:datetime.datetime(2018, 9, 19, 19, 18, 18, 334682)
t = datetime.timedelta(1)
datetime.datetime.now() - t
#結果爲:datetime.datetime(2018, 9, 18, 19, 18, 33, 472953)
datetime.datetime.now() - datetime.timedelta(days=1)
#結果爲:datetime.datetime(2018, 9, 18, 19, 19, 45, 149420)
datetime.datetime.now() - datetime.timedelta(days=4)
#結果爲:datetime.datetime(2018, 9, 15, 19, 19, 57, 147533)
datetime.datetime.now() - datetime.timedelta(hours=3)
#結果爲:datetime.datetime(2018, 9, 19, 16, 20, 17, 150411)
datetime.datetime.now() + datetime.timedelta(hours=3)
#結果爲:datetime.datetime(2018, 9, 19, 22, 20, 29, 46632)
datetime.datetime.now() + datetime.timedelta(minutes=3)
#結果爲:datetime.datetime(2018, 9, 19, 19, 23, 43, 578674)
datetime.datetime.now() + datetime.timedelta(seconds=3)
#結果爲:datetime.datetime(2018, 9, 19, 19, 21, 14, 1416)


#時間替換
datetime.datetime.now()
#結果爲:datetime.datetime(2018, 9, 19, 19, 24, 16, 789861)
d = datetime.datetime.now()
d.replace()
#結果爲:datetime.datetime(2018, 9, 19, 19, 24, 22, 384904)
d.replace(year=2016)
#結果爲:datetime.datetime(2016, 9, 19, 19, 24, 22, 384904)
d.replace(year=2016,month=8)
#結果爲:datetime.datetime(2016, 8, 19, 19, 24, 22, 384904)
d.replace(year=2016,month=8,day=21)
#結果爲:datetime.datetime(2016, 8, 21, 19, 24, 22, 384904)
相關文章
相關標籤/搜索