
- Python 基礎
- Python - 首頁
- Python - 概述
- Python - 歷史
- Python - 特性
- Python vs C++
- Python - Hello World 程式
- Python - 應用領域
- Python - 直譯器
- Python - 環境設定
- Python - 虛擬環境
- Python - 基本語法
- Python - 變數
- Python - 資料型別
- Python - 型別轉換
- Python - Unicode 系統
- Python - 字面量
- Python - 運算子
- Python - 算術運算子
- Python - 比較運算子
- Python - 賦值運算子
- Python - 邏輯運算子
- Python - 位運算子
- Python - 成員運算子
- Python - 身份運算子
- Python - 運算子優先順序
- Python - 註釋
- Python - 使用者輸入
- Python - 數字
- Python - 布林值
- Python 控制語句
- Python - 控制流
- Python - 決策
- Python - If 語句
- Python - If else
- Python - 巢狀 If
- Python - Match-Case 語句
- Python - 迴圈
- Python - for 迴圈
- Python - for-else 迴圈
- Python - While 迴圈
- Python - break 語句
- Python - continue 語句
- Python - pass 語句
- Python - 巢狀迴圈
- Python 函式 & 模組
- Python - 函式
- Python - 預設引數
- Python - 關鍵字引數
- Python - 僅關鍵字引數
- Python - 位置引數
- Python - 僅位置引數
- Python - 可變引數
- Python - 變數作用域
- Python - 函式註解
- Python - 模組
- Python - 內建函式
- Python 字串
- Python - 字串
- Python - 字串切片
- Python - 修改字串
- Python - 字串連線
- Python - 字串格式化
- Python - 跳脫字元
- Python - 字串方法
- Python - 字串練習
- Python 列表
- Python - 列表
- Python - 訪問列表項
- Python - 修改列表項
- Python - 新增列表項
- Python - 刪除列表項
- Python - 迴圈遍歷列表
- Python - 列表推導式
- Python - 對列表排序
- Python - 複製列表
- Python - 合併列表
- Python - 列表方法
- Python - 列表練習
- Python 元組
- Python - 元組
- Python - 訪問元組項
- Python - 更新元組
- Python - 解包元組
- Python - 迴圈遍歷元組
- Python - 合併元組
- Python - 元組方法
- Python - 元組練習
- Python 集合
- Python - 集合
- Python - 訪問集合項
- Python - 新增集合項
- Python - 刪除集合項
- Python - 迴圈遍歷集合
- Python - 合併集合
- Python - 複製集合
- Python - 集合運算子
- Python - 集合方法
- Python - 集合練習
- Python 字典
- Python - 字典
- Python - 訪問字典項
- Python - 修改字典項
- Python - 新增字典項
- Python - 刪除字典項
- Python - 字典檢視物件
- Python - 迴圈遍歷字典
- Python - 複製字典
- Python - 巢狀字典
- Python - 字典方法
- Python - 字典練習
- Python 陣列
- Python - 陣列
- Python - 訪問陣列項
- Python - 新增陣列項
- Python - 刪除陣列項
- Python - 迴圈遍歷陣列
- Python - 複製陣列
- Python - 反轉陣列
- Python - 對陣列排序
- Python - 合併陣列
- Python - 陣列方法
- Python - 陣列練習
- Python 檔案處理
- Python - 檔案處理
- Python - 寫入檔案
- Python - 讀取檔案
- Python - 重新命名和刪除檔案
- Python - 目錄
- Python - 檔案方法
- Python - OS 檔案/目錄方法
- Python - OS 路徑方法
- 面向物件程式設計
- Python - OOPs 概念
- Python - 類 & 物件
- Python - 類屬性
- Python - 類方法
- Python - 靜態方法
- Python - 建構函式
- Python - 訪問修飾符
- Python - 繼承
- Python - 多型
- Python - 方法重寫
- Python - 方法過載
- Python - 動態繫結
- Python - 動態型別
- Python - 抽象
- Python - 封裝
- Python - 介面
- Python - 包
- Python - 內部類
- Python - 匿名類和物件
- Python - 單例類
- Python - 包裝類
- Python - 列舉
- Python - 反射
- Python 錯誤 & 異常
- Python - 語法錯誤
- Python - 異常
- Python - try-except 塊
- Python - try-finally 塊
- Python - 丟擲異常
- Python - 異常連結
- Python - 巢狀 try 塊
- Python - 使用者自定義異常
- Python - 日誌記錄
- Python - 斷言
- Python - 內建異常
- Python 多執行緒
- Python - 多執行緒
- Python - 執行緒生命週期
- Python - 建立執行緒
- Python - 啟動執行緒
- Python - 連線執行緒
- Python - 執行緒命名
- Python - 執行緒排程
- Python - 執行緒池
- Python - 主執行緒
- Python - 執行緒優先順序
- Python - 守護執行緒
- Python - 執行緒同步
- Python 同步
- Python - 執行緒間通訊
- Python - 執行緒死鎖
- Python - 中斷執行緒
- Python 網路
- Python - 網路
- Python - 套接字程式設計
- Python - URL 處理
- Python - 泛型
- Python 庫
- NumPy 教程
- Pandas 教程
- SciPy 教程
- Matplotlib 教程
- Django 教程
- OpenCV 教程
- Python 其他
- Python - 日期 & 時間
- Python - 數學
- Python - 迭代器
- Python - 生成器
- Python - 閉包
- Python - 裝飾器
- Python - 遞迴
- Python - 正則表示式
- Python - PIP
- Python - 資料庫訪問
- Python - 弱引用
- Python - 序列化
- Python - 模板
- Python - 輸出格式化
- Python - 效能測量
- Python - 資料壓縮
- Python - CGI 程式設計
- Python - XML 處理
- Python - GUI 程式設計
- Python - 命令列引數
- Python - 文件字串
- Python - JSON
- Python - 傳送郵件
- Python - 擴充套件
- Python - 工具/實用程式
- Python - GUIs
- Python 高階概念
- Python - 抽象基類
- Python - 自定義異常
- Python - 高階函式
- Python - 物件內部
- Python - 記憶體管理
- Python - 元類
- Python - 使用元類進行超程式設計
- Python - 模擬和存根
- Python - 猴子補丁
- Python - 訊號處理
- Python - 型別提示
- Python - 自動化教程
- Python - Humanize 包
- Python - 上下文管理器
- Python - 協程
- Python - 描述符
- Python - 診斷和修復記憶體洩漏
- Python - 不可變資料結構
- Python 有用資源
- Python - 問答
- Python - 線上測驗
- Python - 快速指南
- Python - 參考
- Python - 速查表
- Python - 專案
- Python - 有用資源
- Python - 討論
- Python 編譯器
- NumPy 編譯器
- Matplotlib 編譯器
- SciPy 編譯器
Python - 日期和時間
Python 程式可以透過多種方式處理日期和時間。在日期格式之間進行轉換是計算機的一項常見任務。Python 標準庫中的以下模組處理與日期和時間相關的處理:
DateTime 模組
Time 模組
Calendar 模組
什麼是 Tick 間隔?
時間間隔是以秒為單位的浮點數。特定時間點以 1970 年 1 月 1 日凌晨 12:00(紀元)以來的秒數表示。
Python 中有一個流行的 time 模組,它提供用於處理時間以及在表示形式之間進行轉換的函式。函式 time.time() 返回自 1970 年 1 月 1 日凌晨 12:00(紀元)以來的系統當前時間(以滴答數表示)。
示例
import time # This is required to include time module. ticks = time.time() print ("Number of ticks since 12:00am, January 1, 1970:", ticks)
這將產生如下結果:
Number of ticks since 12:00am, January 1, 1970: 1681928297.5316436
使用滴答數進行日期運算很容易。但是,在此格式中無法表示紀元之前的日期。未來遙遠的日期也無法以這種方式表示——對於 UNIX 和 Windows,截止點是在 2038 年的某個時候。
什麼是 TimeTuple?
Python 中的許多時間函式都將時間處理為一個包含 9 個數字的元組,如下所示:
索引 | 欄位 | 值 |
---|---|---|
0 | 4 位年份 | 2016 |
1 | 月份 | 1 到 12 |
2 | 日期 | 1 到 31 |
3 | 小時 | 0 到 23 |
4 | 分鐘 | 0 到 59 |
5 | 秒 | 0 到 61(60 或 61 為閏秒) |
6 | 星期幾 | 0 到 6(0 為星期一) |
7 | 一年中的第幾天 | 1 到 366(儒略日) |
8 | 夏令時 | -1、0、1,-1 表示庫確定夏令時 |
例如,
>>>import time >>> print (time.localtime())
這將產生如下 輸出:
time.struct_time(tm_year=2023, tm_mon=4, tm_mday=19, tm_hour=23, tm_min=49, tm_sec=8, tm_wday=2, tm_yday=109, tm_isdst=0)
上述元組等效於 struct_time 結構。此結構具有以下屬性:
索引 | 屬性 | 值 |
---|---|---|
0 | tm_year | 2016 |
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(60 或 61 為閏秒) |
6 | tm_wday | 0 到 6(0 為星期一) |
7 | tm_yday | 1 到 366(儒略日) |
8 | tm_isdst | -1、0、1,-1 表示庫確定夏令時 |
獲取當前時間
要將自紀元以來的時間點(浮點數)轉換為時間元組,請將浮點數傳遞給一個返回包含所有 9 個有效項的時間元組的函式(例如,localtime)。
import time localtime = time.localtime(time.time()) print ("Local current time :", localtime)
這將產生以下結果,該結果可以格式化為任何其他可呈現的形式:
Local current time : time.struct_time(tm_year=2023, tm_mon=4, tm_mday=19, tm_hour=23, tm_min=42, tm_sec=41, tm_wday=2, tm_yday=109, tm_isdst=0)
獲取格式化的時間
您可以根據需要格式化任何時間,但獲取易讀格式時間的一種簡單方法是 asctime():
import time localtime = time.asctime( time.localtime(time.time()) ) print ("Local current time :", localtime)
這將產生以下 輸出:
Local current time : Wed Apr 19 23:45:27 2023
獲取一個月的日曆
calendar 模組提供了廣泛的方法來處理年曆和月曆。在這裡,我們列印給定月份(2008 年 1 月)的日曆。
import calendar cal = calendar.month(2023, 4) print ("Here is the calendar:") print (cal)
這將產生以下 輸出:
Here is the calendar: April 2023 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
Time 模組
Python 中有一個流行的 time 模組,它提供用於處理時間以及在表示形式之間進行轉換的函式。以下是所有可用方法的列表。
序號 | 函式及描述 |
---|---|
1 | time.altzone
如果定義了本地夏令時時區,則其相對於 UTC 的偏移量(以秒為單位),如果定義了該時區。如果本地夏令時時區位於 UTC 以東(如西歐,包括英國),則為負數。僅當 daylight 非零時使用此值。 |
2 | time.asctime([tupletime])
接受時間元組並返回一個可讀的 24 個字元的字串,例如“Tue Dec 11 18:07:14 2008”。 |
3 | time.clock( )
以秒為單位的浮點數形式返回當前 CPU 時間。為了衡量不同方法的計算成本,time.clock 的值比 time.time 的值更有用。 |
4 | time.ctime([secs])
類似於 asctime(localtime(secs)),並且在沒有引數的情況下類似於 asctime( ) |
5 | time.gmtime([secs])
接收自紀元以來的秒數表示的時刻,並返回一個包含 UTC 時間的 time-tuple t。注意:t.tm_isdst 始終為 0。 |
6 | time.localtime([secs])
接收自紀元以來的秒數表示的時刻,並返回一個包含本地時間(t.tm_isdst 為 0 或 1,取決於本地規則是否將 DST 應用於時刻 secs)的 time-tuple t。 |
7 | time.mktime(tupletime)
接收以本地時間表示的 time-tuple 表示的時刻,並返回一個浮點數,該浮點數表示自紀元以來的秒數。 |
8 | time.sleep(secs)
掛起呼叫執行緒 secs 秒。 |
9 | time.strftime(fmt[,tupletime])
接收以本地時間表示的 time-tuple 表示的時刻,並返回一個字串,該字串根據字串 fmt 指定的格式表示該時刻。 |
10 | time.strptime(str,fmt='%a %b %d %H:%M:%S %Y')
根據格式字串 fmt 解析 str,並以 time-tuple 格式返回該時刻。 |
11 | time.time( )
返回當前時刻,一個自紀元以來的秒數的浮點數。 |
12 | time.tzset()
重置庫例程使用的時區轉換規則。環境變數 TZ 指定如何執行此操作。 |
讓我們簡要介紹一下這些函式。
time 模組有兩個重要的可用屬性。它們是:
序號 | 帶描述的屬性 |
---|---|
1 | time.timezone 屬性 time.timezone 是本地時區(不含夏令時)相對於 UTC 的偏移量(在美洲 >0;在歐洲、亞洲、非洲的大部分地區 <=0)。 |
2 | time.tzname 屬性 time.tzname 是一對依賴於區域設定的字串,分別是本地時區分別不含和含夏令時的名稱。 |
calendar 模組
calendar 模組提供與日曆相關的函式,包括列印給定月份或年份的文字日曆的函式。
預設情況下,calendar 將星期一作為一週的第一天,星期日作為最後一天。要更改此設定,請呼叫 **calendar.setfirstweekday()** 函式。
以下是 **calendar** 模組提供的函式列表:
序號 | 函式及描述 |
---|---|
1 | calendar.calendar(year,w=2,l=1,c=6) 返回一個多行字串,其中包含 year 年份的日曆,格式化為三列,列之間用 c 個空格分隔。w 是每個日期的字元寬度;每行的長度為 21*w+18+2*c。l 是每個星期的行數。 |
2 | calendar.firstweekday( ) 返回每個星期開始的星期幾的當前設定。預設情況下,當首次匯入 calendar 時,此值為 0,表示星期一。 |
3 | calendar.isleap(year) 如果 year 是閏年,則返回 True;否則返回 False。 |
4 | calendar.leapdays(y1,y2) 返回 range(y1,y2) 中年份內的閏年總數。 |
5 | calendar.month(year,month,w=2,l=1) 返回一個多行字串,其中包含 year 年份 month 月份的日曆,每行一個星期,加上兩行標題。w 是每個日期的字元寬度;每行的長度為 7*w+6。l 是每個星期的行數。 |
6 | calendar.monthcalendar(year,month) 返回一個整數列表的列表。每個子列表表示一個星期。year 年份 month 月份之外的天數設定為 0;月份內的天數設定為其月份中的日期,從 1 開始。 |
7 | calendar.monthrange(year,month) 返回兩個整數。第一個是 year 年份 month 月份的第一天的星期幾程式碼;第二個是該月份的天數。星期幾程式碼為 0(星期一)到 6(星期日);月份數字為 1 到 12。 |
8 | calendar.prcal(year,w=2,l=1,c=6) 類似於 print calendar.calendar(year,w,l,c)。 |
9 | calendar.prmonth(year,month,w=2,l=1) 類似於 print calendar.month(year,month,w,l)。 |
10 | calendar.setfirstweekday(weekday) 將每個星期的第一天設定為星期幾程式碼 weekday。星期幾程式碼為 0(星期一)到 6(星期日)。 |
11 | calendar.timegm(tupletime) time.gmtime 的反函式:接收 time-tuple 形式的時刻,並返回自紀元以來的秒數的浮點數,表示同一時刻。 |
12 | calendar.weekday(year,month,day) 返回給定日期的星期幾程式碼。星期幾程式碼為 0(星期一)到 6(星期日);月份數字為 1(一月)到 12(十二月)。 |
Python datetime 模組
Python 的 datetime 模組包含在標準庫中。它包含有助於操作資料和時間資料並執行日期時間算術的類。
datetime 類的物件要麼是已知的,要麼是樸素的。如果物件包含時區資訊,則它是已知的,否則它被歸類為樸素的。date 類物件是樸素的,而 time 和 datetime 物件是已知的。
Python date 物件
date 物件表示一個日期,包括年份、月份和日期。當前的格里高利曆法在兩個方向上無限期地擴充套件。
語法
datetime.date(year, month, day)
引數必須是整數,在以下範圍內:
**year** − MINYEAR <= year <= MAXYEAR
**month** − 1 <= month <= 12
**day** − 1 <= day <= 給定月份和年份中的天數
如果任何引數的值超出這些範圍,則會引發 ValueError。
示例
from datetime import date date1 = date(2023, 4, 19) print("Date:", date1) date2 = date(2023, 4, 31)
它將產生以下 **輸出**:
Date: 2023-04-19 Traceback (most recent call last): File "C:\Python311\hello.py", line 8, in <module> date2 = date(2023, 4, 31) ValueError: day is out of range for month
date 類屬性
**date.min** − 可表示的最早日期,date(MINYEAR, 1, 1)。
**date.max** − 可表示的最新日期,date(MAXYEAR, 12, 31)。
**date.resolution** − 非相等 date 物件之間可能的最小差異。
**date.year** − 包含在 MINYEAR 和 MAXYEAR 之間。
**date.month** − 包含在 1 和 12 之間。
**date.day** − 包含在 1 和給定年份的給定月份的天數之間。
示例
from datetime import date # Getting min date mindate = date.min print("Minimum Date:", mindate) # Getting max date maxdate = date.max print("Maximum Date:", maxdate) Date1 = date(2023, 4, 20) print("Year:", Date1.year) print("Month:", Date1.month) print("Day:", Date1.day)
它將產生以下 **輸出**:
Minimum Date: 0001-01-01 Maximum Date: 9999-12-31 Year: 2023 Month: 4 Day: 20
Date 類中的類方法
**today()** − 返回當前本地日期。
**fromtimestamp(timestamp)** − 返回對應於 POSIX 時間戳的本地日期,例如 time.time() 返回的日期。
**fromordinal(ordinal)** − 返回對應於前格里高利序數的日期,其中年份 1 的 1 月 1 日的序數為 1。
**fromisoformat(date_string)** − 返回對應於以任何有效的 ISO 8601 格式給定的 date_string 的日期,除了序數日期
示例
from datetime import date print (date.today()) d1=date.fromisoformat('2023-04-20') print (d1) d2=date.fromisoformat('20230420') print (d2) d3=date.fromisoformat('2023-W16-4') print (d3)
它將產生以下 **輸出**:
2023-04-20 2023-04-20 2023-04-20 2023-04-20
Date 類中的例項方法
**replace()** − 透過關鍵字引數指定的新值替換指定的屬性,返回一個日期。
**timetuple()** − 返回一個 time.struct_time,例如 time.localtime() 返回的。
**toordinal()** − 返回日期的前格里高利序數,其中年份 1 的 1 月 1 日的序數為 1。對於任何日期物件 d,date.fromordinal(d.toordinal()) == d。
**weekday()** − 將一週中的某一天作為整數返回,其中星期一為 0,星期日為 6。
**isoweekday()** − 將一週中的某一天作為整數返回,其中星期一為 1,星期日為 7。
**isocalendar()** − 返回一個命名元組物件,包含三個元件:年份、星期和星期幾。
**isoformat()** − 返回一個字串,表示以 ISO 8601 格式 YYYY-MM-DD 表示的日期
**__str__()** − 對於日期 d,str(d) 等效於 d.isoformat()
**ctime()** − 返回一個表示日期的字串
**strftime(format)** − 返回一個表示日期的字串,由顯式格式字串控制。
**__format__(format)** − 與 date.strftime() 相同。
示例
from datetime import date d = date.fromordinal(738630) # 738630th day after 1. 1. 0001 print (d) print (d.timetuple()) # Methods related to formatting string output print (d.isoformat()) print (d.strftime("%d/%m/%y")) print (d.strftime("%A %d. %B %Y")) print (d.ctime()) print ('The {1} is {0:%d}, the {2} is {0:%B}.'.format(d, "day", "month")) # Methods for to extracting 'components' under different calendars t = d.timetuple() for i in t: print(i) ic = d.isocalendar() for i in ic: print(i) # A date object is immutable; all operations produce a new object print (d.replace(month=5))
它將產生以下 **輸出**:
2023-04-20 time.struct_time(tm_year=2023, tm_mon=4, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=110, tm_isdst=-1) 2023-04-20 20/04/23 Thursday 20. April 2023 Thu Apr 20 00:00:00 2023 The day is 20, the month is April. 2023 4 20 0 0 0 3 110 -1 2023 16 4 2023-05-20
Python time 模組
time 類物件表示一天中的本地時間。它獨立於任何特定的一天。如果物件包含 tzinfo 詳細資訊,則它是已知物件。如果為 None,則 time 物件是樸素物件。
語法
datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
所有引數都是可選的。tzinfo 可以是 None,也可以是 tzinfo 子類的例項。其餘引數必須是以下範圍內的整數:
**hour** − 0 <= hour < 24,
**minute** − 0 <= minute < 60,
**second** − 0 <= second < 60,
**microsecond** − 0 <= microsecond < 1000000
如果任何引數的值超出這些範圍,則會引發 ValueError。
示例
from datetime import time time1 = time(8, 14, 36) print("Time:", time1) time2 = time(minute = 12) print("time", time2) time3 = time() print("time", time3) time4 = time(hour = 26)
它將產生以下 **輸出**:
Time: 08:14:36 time 00:12:00 time 00:00:00 Traceback (most recent call last): File "/home/cg/root/64b912f27faef/main.py", line 12, intime4 = time(hour = 26) ValueError: hour must be in 0..23
類屬性
**time.min** − 可表示的最早時間,time(0, 0, 0, 0)。
**time.max** − 可表示的最新時間,time(23, 59, 59, 999999)。
**time.resolution** − 非相等 time 物件之間可能的最小差異。
示例
from datetime import time print(time.min) print(time.max) print (time.resolution)
它將產生以下 **輸出**:
00:00:00 23:59:59.999999 0:00:00.000001
例項屬性
**time.hour** − 在 range(24) 中
**time.minute** − 在 range(60) 中
**time.second** − 在 range(60) 中
**time.microsecond** − 在 range(1000000) 中
**time.tzinfo** − 傳遞給 time 建構函式的 tzinfo 引數,或 None。
示例
from datetime import time t = time(8,23,45,5000) print(t.hour) print(t.minute) print (t.second) print (t.microsecond)
它將產生以下 **輸出**:
8 23 455000
time 物件的例項方法
**replace()** − 返回具有相同值的時間,但由任何指定的關鍵字引數賦予新值的屬性除外。
**isoformat()** − 返回一個字串,表示以 ISO 8601 格式表示的時間
**__str__()** − 對於時間 t,str(t) 等效於 t.isoformat()。
**strftime(format)** − 返回一個字串,表示由顯式格式字串控制的時間。
**__format__(format)** − 與 time.strftime() 相同。
**utcoffset()** − 如果 tzinfo 為 None,則返回 None,否則返回 self.tzinfo.utcoffset(None),
**dst()** − 如果 tzinfo 為 None,則返回 None,否則返回 self.tzinfo.dst(None),
**tzname()** − 如果 tzinfo 為 None,則返回 None,否則返回 self.tzinfo.tzname(None),或引發異常
Python datetime 物件
datetime 類物件包含日期和時間的資訊。它假設當前的格里高利曆法在兩個方向上無限期地擴充套件;就像 time 物件一樣,並且每一天正好有 3600*24 秒。
語法
datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)
年份、月份和日期引數是必需的。
**year** − MINYEAR <= year <= MAXYEAR,
**month** − 1 <= month <= 12,
**day** − 1 <= day <= 給定月份和年份中的天數,
**hour** − 0 <= hour < 24,
**minute** − 0 <= minute < 60,
**second** −0 <= second < 60,
**microsecond** − 0 <= microsecond < 1000000,
**fold** − 在 [0, 1] 中。
如果任何引數的值超出範圍,則會引發 ValueError。
示例
from datetime import datetime dt = datetime(2023, 4, 20) print(dt) dt = datetime(2023, 4, 20, 11, 6, 32, 5000) print(dt)
它將產生以下 **輸出**:
2023-04-20 00:00:00 2023-04-20 11:06:32.005000
類屬性
**datetime.min** − 可表示的最早 datetime,datetime(MINYEAR, 1, 1, tzinfo=None)。
**datetime.max** − 可表示的最新 datetime,datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)。
**datetime.resolution** − 非相等 datetime 物件之間可能的最小差異,timedelta(microseconds=1)。
示例
from datetime import datetime min = datetime.min print("Min DateTime ", min) max = datetime.max print("Max DateTime ", max)
它將產生以下 **輸出**:
Min DateTime 0001-01-01 00:00:00 Max DateTime 9999-12-31 23:59:59.999999
datetime 物件的例項屬性
**datetime.year** − 包含在 MINYEAR 和 MAXYEAR 之間。
**datetime.month** − 包含在 1 和 12 之間。
**datetime.day** − 包含在 1 和給定年份的給定月份的天數之間。
**datetime.hour** − 在 range(24) 中
**datetime.minute** − 在 range(60) 中
**datetime.second** − 在 range(60) 中
**datetime.microsecond** − 在 range(1000000) 中。
**datetime.tzinfo** − 傳遞給 datetime 建構函式的 tzinfo 物件,或者如果未傳遞則為 None。
**datetime.fold** − 在 [0, 1] 中。用於在重複間隔期間消除牆時間的歧義。
示例
from datetime import datetime dt = datetime.now() print("Day: ", dt.day) print("Month: ", dt.month) print("Year: ", dt.year) print("Hour: ", dt.hour) print("Minute: ", dt.minute) print("Second: ", dt.second)
它將產生以下 **輸出**:
Day: 20 Month: 4 Year: 2023 Hour: 15 Minute: 5 Second: 52
datetime 物件的類方法
**today()** − 返回當前本地 datetime,tzinfo 為 None。
**now(tz=None)** − 返回當前本地日期和時間。
**utcnow()** − 返回當前 UTC 日期和時間,tzinfo 為 None。
**utcfromtimestamp(timestamp)** − 返回對應於 POSIX 時間戳的 UTC datetime,tzinfo 為 None
fromtimestamp(timestamp, timezone.utc) − 在 POSIX 相容平臺上,它等價於 datetime(1970, 1, 1, tzinfo=timezone.utc) + timedelta(seconds=timestamp)
fromordinal(ordinal) − 返回對應於前儒略曆序數的 datetime 物件,其中公元 1 年 1 月 1 日的序數為 1。
fromisoformat(date_string) − 返回對應於任何有效 ISO 8601 格式的 date_string 的 datetime 物件。
datetime 物件的例項方法
date() − 返回具有相同年、月和日的 date 物件。
time() − 返回具有相同小時、分鐘、秒、微秒和 fold 屬性的 time 物件。
timetz() − 返回具有相同小時、分鐘、秒、微秒、fold 和 tzinfo 屬性的 time 物件。另請參見方法 time()。
replace() − 返回一個具有相同屬性的 datetime 物件,除了透過指定的關鍵字引數賦予新值的那些屬性。
astimezone(tz=None) − 返回一個具有新的 tzinfo 屬性 tz 的 datetime 物件
utcoffset() − 如果 tzinfo 為 None,則返回 None,否則返回 self.tzinfo.utcoffset(self)
dst() − 如果 tzinfo 為 None,則返回 None,否則返回 self.tzinfo.dst(self)
tzname() − 如果 tzinfo 為 None,則返回 None,否則返回 self.tzinfo.tzname(self)
**timetuple()** − 返回一個 time.struct_time,例如 time.localtime() 返回的。
datetime.toordinal() − 返回日期的前儒略曆序數。
timestamp() − 返回對應於 datetime 例項的 POSIX 時間戳。
isoweekday() − 返回一週中的某一天作為整數,其中星期一為 1,星期日為 7。
isocalendar() − 返回一個包含三個元件的命名元組:年、周和星期幾。
isoformat(sep='T', timespec='auto') − 返回一個以 ISO 8601 格式表示日期和時間的字串
__str__() − 對於 datetime 例項 d,str(d) 等價於 d.isoformat(' ')。
ctime() − 返回一個表示日期和時間的字串
strftime(format) − 返回一個表示日期和時間的字串,由一個顯式格式字串控制。
__format__(format) − 與 strftime() 相同。
示例
from datetime import datetime, date, time, timezone # Using datetime.combine() d = date(2022, 4, 20) t = time(12, 30) datetime.combine(d, t) # Using datetime.now() d = datetime.now() print (d) # Using datetime.strptime() dt = datetime.strptime("23/04/20 16:30", "%d/%m/%y %H:%M") # Using datetime.timetuple() to get tuple of all attributes tt = dt.timetuple() for it in tt: print(it) # Date in ISO format ic = dt.isocalendar() for it in ic: print(it)
它將產生以下 **輸出**:
2023-04-20 15:12:49.816343 2020 4 23 16 30 0 3 114 -1 2020 17 4
Python timedelta 物件
timedelta 物件表示兩個日期或兩個時間物件之間的持續時間。
語法
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
在內部,屬性儲存在天、秒和微秒中。其他引數將轉換為這些單位 −
毫秒轉換為 1000 微秒。
分鐘轉換為 60 秒。
小時轉換為 3600 秒。
週轉換為 7 天。
然後對天、秒和微秒進行標準化,以便表示唯一。
示例
以下示例顯示 Python 在內部僅儲存天、秒和微秒。
from datetime import timedelta delta = timedelta( days=100, seconds=27, microseconds=10, milliseconds=29000, minutes=5, hours=12, weeks=2 ) # Only days, seconds, and microseconds remain print (delta)
它將產生以下 **輸出**:
114 days, 12:05:56.000010
示例
以下示例顯示如何將 timedelta 物件新增到 datetime 物件。
from datetime import datetime, timedelta date1 = datetime.now() date2= date1+timedelta(days = 4) print("Date after 4 days:", date2) date3 = date1-timedelta(15) print("Date before 15 days:", date3)
它將產生以下 **輸出**:
Date after 4 days: 2023-04-24 18:05:39.509905 Date before 15 days: 2023-04-05 18:05:39.509905
timedelta 物件的類屬性
timedelta.min − 最小的 timedelta 物件,timedelta(-999999999)。
timedelta.max − 最大的 timedelta 物件,timedelta(days=999999999, hours=23, minutes=59, seconds=59, microseconds=999999)。
timedelta.resolution − 不相等 timedelta 物件之間可能的最小差異,timedelta(microseconds=1)
示例
from datetime import timedelta # Getting minimum value min = timedelta.min print("Minimum value:", min) max = timedelta.max print("Maximum value", max)
它將產生以下 **輸出**:
Minimum value: -999999999 days, 0:00:00 Maximum value 999999999 days, 23:59:59.999999
timedelta 物件的例項屬性
由於內部只儲存天、秒和微秒,因此這些是 timedelta 物件的唯一例項屬性。
days − 在 -999999999 到 999999999(含)之間
seconds − 在 0 到 86399(含)之間
microseconds − 在 0 到 999999(含)之間
timedelta 物件的例項方法
timedelta.total_seconds() − 返回持續時間中包含的秒數總和。
示例
from datetime import timedelta year = timedelta(days=365) years = 5 * year print (years) print (years.days // 365) 646 year_1 = years // 5 print(year_1.days)
它將產生以下 **輸出**:
1825 days, 0:00:00 5 365