1. 程式人生 > >Python筆記:datetime模組

Python筆記:datetime模組

Python提供了多個內建模組用於操作日期時間,像calendar,time,datetime。time模組我在之前的文章已經有所介紹,它提供 的介面與C標準庫time.h基本一致。相比於time模組,datetime模組的介面則更直觀、更容易呼叫。今天就來講講datetime模組。

    datetime模組定義了兩個常量:datetime.MINYEAR和datetime.MAXYEAR,分別表示datetime所能表示的最 小、最大年份。其中,MINYEAR = 1,MAXYEAR = 9999。(對於偶等玩家,這個範圍已經足夠用矣~~)

    datetime模組定義了下面這幾個類:

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

     :上面這些型別的物件都是不可變(immutable)的。

    下面詳細介紹這些類的使用方式。

date類

    date類表示一個日期。日期由年、月、日組成(地球人都知道~~)。date類的建構函式如下:

    class datetime.date(year, month, day):引數的意義就不多作解釋了,只是有幾點要注意一下:

  • year的範圍是[MINYEAR, MAXYEAR],即[1, 9999];
  • month的範圍是[1, 12]。(月份是從1開始的,不是從0開始的~_~);
  • day的最大值根據給定的year, month引數來決定。例如閏年2月份有29天;

    date類定義了一些常用的類方法與類屬性,方便我們操作:

  • date.max、date.min:date物件所能表示的最大、最小日期;
  • date.resolution:date物件表示日期的最小單位。這裡是天。
  • date.today():返回一個表示當前本地日期的date物件;
  • date.fromtimestamp(timestamp):根據給定的時間戮,返回一個date物件;
  • datetime.fromordinal(ordinal):將Gregorian日曆時間轉換為date物件;(Gregorian Calendar :一種日曆表示方法,類似於我國的農曆,西方國家使用比較多,此處不詳細展開討論。)

    使用例子:

  1. from  datetime  import  *  
  2. import  time  
  3. print   'date.max:' , date.max  
  4. print   'date.min:' , date.min  
  5. print   'date.today():' , date.today()  
  6. print   'date.fromtimestamp():' , date.fromtimestamp(time.time())  
  7. # # ---- 結果 ----   
  8. # date.max: 9999-12-31   
  9. # date.min: 0001-01-01   
  10. # date.today(): 2010-04-06   
  11. # date.fromtimestamp(): 2010-04-06   
  1. from datetime import *  
  2. import time  
  3. print 'date.max:', date.max  
  4. print 'date.min:', date.min  
  5. print 'date.today():', date.today()  
  6. print 'date.fromtimestamp():', date.fromtimestamp(time.time())  
  7. # # ---- 結果 ----  
  8. # date.max: 9999-12-31  
  9. # date.min: 0001-01-01  
  10. # date.today(): 2010-04-06  
  11. # date.fromtimestamp(): 2010-04-06  

    date提供的例項方法和屬性:

  • date.year、date.month、date.day:年、月、日;
  • date.replace(year, month, day):生成一個新的日期物件,用引數指定的年,月,日代替原有物件中的屬性。(原有物件仍保持不變)
  • date.timetuple():返回日期對應的time.struct_time物件;
  • date.toordinal():返回日期對應的Gregorian Calendar日期;
  • date.weekday():返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此類推;
  • data.isoweekday():返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此類推;
  • date.isocalendar():返回格式如(year,month,day)的元組;
  • date.isoformat():返回格式如'YYYY-MM-DD’的字串;
  • date.strftime(fmt):自定義格式化字串。在下面詳細講解。

    使用例子:

  1. now = date( 2010 ,  04 ,  06 )  
  2. tomorrow = now.replace(day = 07 )  
  3. print   'now:' , now,  ', tomorrow:' , tomorrow  
  4. print   'timetuple():' , now.timetuple()  
  5. print   'weekday():' , now.weekday()  
  6. print   'isoweekday():' , now.isoweekday()  
  7. print   'isocalendar():' , now.isocalendar()  
  8. print   'isoformat():' , now.isoformat()  
  9. # # ---- 結果 ----   
  10. # now: 2010-04-06 , tomorrow: 2010-04-07   
  11. # timetuple(): (2010, 4, 6, 0, 0, 0, 1, 96, -1)   
  12. # weekday(): 1   
  13. # isoweekday(): 2   
  14. # isocalendar(): (2010, 14, 2)   
  15. # isoformat(): 2010-04-06   
  1. now = date(20100406)  
  2. tomorrow = now.replace(day = 07)  
  3. print 'now:', now, ', tomorrow:', tomorrow  
  4. print 'timetuple():', now.timetuple()  
  5. print 'weekday():', now.weekday()  
  6. print 'isoweekday():', now.isoweekday()  
  7. print 'isocalendar():', now.isocalendar()  
  8. print 'isoformat():', now.isoformat()  
  9. # # ---- 結果 ----  
  10. # now: 2010-04-06 , tomorrow: 2010-04-07  
  11. # timetuple(): (2010, 4, 6, 0, 0, 0, 1, 96, -1)  
  12. # weekday(): 1  
  13. # isoweekday(): 2  
  14. # isocalendar(): (2010, 14, 2)  
  15. # isoformat(): 2010-04-06  

    date還對某些操作進行了過載,它允許我們對日期進行如下一些操作:

  • date2 = date1 + timedelta  # 日期加上一個間隔,返回一個新的日期物件(timedelta將在下面介紹,表示時間間隔)
  • date2 = date1 - timedelta   # 日期隔去間隔,返回一個新的日期物件
  • timedelta = date1 - date2   # 兩個日期相減,返回一個時間間隔物件
  • date1 < date2  # 兩個日期進行比較

    注: 對日期進行操作時,要防止日期超出它所能表示的範圍。

    使用例子:

  1. now = date.today()  
  2. tomorrow = now.replace(day = 7 )  
  3. delta = tomorrow - now  
  4. print   'now:' , now,  ' tomorrow:' , tomorrow  
  5. print   'timedelta:' , delta  
  6. print  now + delta  
  7. print  tomorrow > now  
  8. # # ---- 結果 ----   
  9. # now: 2010-04-06  tomorrow: 2010-04-07   
  10. # timedelta: 1 day, 0:00:00   
  11. # 2010-04-07   
  12. # True   
  1. now = date.today()  
  2. tomorrow = now.replace(day = 7)  
  3. delta = tomorrow - now  
  4. print 'now:', now, ' tomorrow:', tomorrow  
  5. print 'timedelta:', delta  
  6. print now + delta  
  7. print tomorrow > now  
  8. # # ---- 結果 ----  
  9. # now: 2010-04-06  tomorrow: 2010-04-07  
  10. # timedelta: 1 day, 0:00:00  
  11. # 2010-04-07  
  12. # True  

Time類

    time類表示時間,由時、分、秒以及微秒組成。(我不是從火星來的~~)time類的建構函式如下:

    class datetime.time(hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ) :各引數的意義不作解釋,這裡留意一下引數tzinfo,它表示時區資訊。注意一下各引數的取值範圍:hour的範圍為[0, 24),minute的範圍為[0, 60),second的範圍為[0, 60),microsecond的範圍為[0, 1000000)。

    time類定義的類屬性:

  • time.min、time.max:time類所能表示的最小、最大時間。其中,time.min = time(0, 0, 0, 0), time.max = time(23, 59, 59, 999999);
  • time.resolution:時間的最小單位,這裡是1微秒;

    time類提供的例項方法和屬性:

  • time.hour、time.minute、time.second、time.microsecond:時、分、秒、微秒;
  • time.tzinfo:時區資訊;
  • time.replace([ hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ):建立一個新的時間物件,用引數指定的時、分、秒、微秒代替原有物件中的屬性(原有物件仍保持不變);
  • time.isoformat():返回型如"HH:MM:SS"格式的字串表示;
  • time.strftime(fmt):返回自定義格式化字串。在下面詳細介紹;

使用例子:

  1. from  datetime  import  *  
  2. tm = time(23 ,  46 ,  10 )  
  3. print   'tm:' , tm  
  4. 相關推薦

    Python筆記datetime模組

    Python提供了多個內建模組用於操作日期時間,像calendar,time,datetime。time模組我在之前的文章已經有所介紹,它提供 的介面與C標準庫time.h基本一致。相比於time模組,datetime模組的介面則更直觀、更容易呼叫。今天就來講講dat

    Python學習筆記bisect模組實現二分搜尋

      在Python中可以利用bisect模組來實現二分搜尋,該模組包含函式只有幾個: import bisect L = [1,3,4,5,5,5,8,10] x = 5 bisect.bisect_left(L,x) # 3 # 在L中查詢x,x存在時返回x最左側的位置,x不存在返回應該插入

    Python 學習筆記 Logging 模組

    Logging 模組 import logging logger = logging.getLogger() # 建立一個handler,用於寫入日誌檔案 fh = logging.FileHandler('test.log',encoding='utf-8') # 再建立一個handler,用於

    python筆記1.安裝以及安裝模組

    一、Python軟體安裝 當前Python大致可分為Python2.7以及Python3,如果是首次上手建議選擇Python3,因為Python2.7和Python3有著不小的差別,並且Python2.7漸漸被丟棄。。。 a.下載 以下是Python官網下載地址,可以根據電腦的作業系統以

    Pythondatetime模組使用

    #!/usr/bin/env python # coding:UTF-8 """ @version: python3.x @author:曹新健 @contact: [email protected] @software: PyCharm @file: date

    Python scikit-learn機器學習工具包學習筆記cross_validation模組

    sklearn.cross_validation模組的作用顧名思義就是做cross validation的。 cross validation大概的意思是:對於原始資料我們要將其一部分分為train data,一部分分為test data。train data用於訓練,

    guxh的python筆記包和模組

    1,包和模組 包package:本質就是一個資料夾/目錄,必須帶一個__init.__.py的檔案 模組module:.py結尾的python檔案   2,匯入方法 import pandas, collections  # 匯入多個 import pandas as

    python筆記購物車

    python 購物車product_list=[ (,), (,), (,), (,), (,), (,), ] shopping_list = []salary = ()salary.isdigit():salary =(salary) :

    嵩天老師的零基礎Python筆記https://www.bilibili.com/video/av13570243/?from=search&seid=15873837810484552531 中的15-22講

    lock dia 自然常數e list 隨機種子 返回 時間 三種 lis #coding=gbk#嵩天老師的零基礎Python筆記:https://www.bilibili.com/video/av13570243/?from=search&seid=158738

    嵩天老師的零基礎Python筆記https://www.bilibili.com/video/av15123607/?from=search&seid=10211084839195730432#page=25 中的30-34講

    positive 浮點型 was format 零基礎 判斷 筆記 提示 返回值 #coding=gbk#嵩天老師的零基礎Python筆記:https://www.bilibili.com/video/av15123607/?from=search&seid=102

    嵩天老師的零基礎Python筆記https://www.bilibili.com/video/av15123607/?from=search&seid=10211084839195730432#page=25 中的38-41講

    col turtle 計算 正則表達式 __main__ 打開文件 video 照片 itl # -*- coding: utf-8 -*-#嵩天老師的零基礎Python筆記:https://www.bilibili.com/video/av15123607/?from=s

    python筆記深淺拷貝

    深淺拷貝 port 指針 pre 淺拷貝 In 獨立 imp col #淺拷貝s = [‘1‘, ‘test‘, 2, {1: ‘wen‘}, [1, 3]]s2 = s.copy() #拷貝 copy()print(s)print(s2)s2[2] = 5

    Python筆記函數的遞歸

    代碼 com 垃圾回收機制 遞歸函數 size 兩個 logs htm rdquo 遞歸函數 recursion 遞歸是指函數直接或間接的調用自身 遞歸實例: #函數直接調用自身 def f(): f()直接調用自身 f() pr

    Python PrettyTable 模組

    一,PrettyTable簡介 PrettyTable是python中的一個第三方庫,可用來生成美觀的ASCII格式的表格: 二,PrettyTable安裝 使用PIP即可十分方便的安裝PrettyTable,如下: pip install prettytable 三,PrettyTable匯入&nbs

    python筆記 類中的__str__ 函式

    如果要把一個類的例項變成 str,就需要實現特殊方法__str__(): 不使用__str()__ 時 class Member: def __init__(self , name , number): self.name = name s

    python筆記 經典類和新式類的區別

    python 筆記:經典類和新式類的區別 Python 2.x中預設都是經典類,只有顯式繼承了object才是新式類 Python 3.x中預設都是新式類,不必顯式的繼承object 其次: ——新式類物件可以直接通過class屬性獲取自身型別:type ——繼承搜

    Python程式設計operator模組包含的函式

    operator模組主要包括一些python內部操作符對應的函式 主要包括幾類: 算術運算 位運算 序列操作 邏輯比較 物件比較 算術運算 操作 語法 函式

    opencv-python(十三)DNN模組載入caffe訓練好的SSD模型

        opencv越來越強大了,可以直接對訓練好的caffe、tensorflow等框架訓練好的模型進行載入,進而完成識別、檢測等任務。     opencv載入caffe訓練好的模型,採用readNetFromCaffe(arg1,arg2),第一個引數對應定義模型結構

    python筆記清楚理解判斷語句if __name__ == "__main__"

    if __name__ == "__main__":應該怎麼樣理解呢? stackoverfolow社群活動參考答案在這裡。由 Mr Fooz在2009-1-17回答: 首先,什麼是 __name__? __name__是一個DunderAlisa。在module層

    Python爬蟲lxml模組分析並獲取網頁內容

    運用css選擇器: # -*- coding: utf-8 -*- from lxml import html page_html = ''' <html><body> <input id="input_id" value="input value" nam