Python 日期和時間用法超強總結
時間無疑是生活各個方面中最關鍵的因素之一,因此,記錄和跟蹤時間變得非常重要。在 Python 中,可以通過其內置庫跟蹤日期和時間。今天我們來介紹關于 Python 中的日期和時間,一起來了解如何使用time和datetime模塊查找和修改日期和時間。
Python 中處理日期和時間的模塊
Python 提供了time和datetime模塊,可以幫助我們輕松獲取和修改日期和時間,下面讓我們來逐一了解一下。
time 模塊
該模塊包括使用時間執行各種操作所需的所有與時間相關的功能,它還允許我們訪問多種用途所需的時鐘類型。
內置函數:
請看下表,它描述了時間模塊的一些重要內置功能。
function | Description |
time() | 返回自epoch以來經過的秒數 |
ctime() | 以經過的秒數作為參數,返回當前日期和時間 |
sleep() | 在給定的持續時間內停止線程的執行 |
time.struct_time Class | 函數要么將此類作為參數,要么將其作為輸出返回 |
localtime() | 以自epoch以來經過的秒數作為參數,并以時間形式返回日期和時間。struct_time格式 |
gmtime() | 與localtime()類似,返回時間。UTC格式的struct_time |
mktime() | ocaltime()的倒數。獲取包含9個參數的元組,并返回自epoch pas輸出以來經過的秒數 |
asctime() | 獲取包含9個參數的元組,并返回表示相同參數的字符串 |
strftime() | 獲取包含9個參數的元組,并根據使用的格式代碼返回表示相同參數的字符串 |
strptime() | 分析字符串并及時返回。struct_time格式 |
代碼格式化:
在用示例解釋每個函數之前,先看一下所有合法的格式化代碼的方式:
Code | Description | Example |
%a | Weekday (short version) | Mon |
%A | Weekday (full version) | Monday |
%b | Month (short version) | Aug |
%B | Month (full version) | August |
%c | Local date and time version | Tue Aug 23 1:31:40 2019 |
%d | Depicts the day of the month (01-31) | 07 |
%f | Microseconds | 000000-999999 |
%H | Hour (00-23) | 15 |
%I | Hour (00-11) | 3 |
%j | Day of the year | 235 |
%m | Month Number (01-12) | 07 |
%M | Minutes (00-59) | 44 |
%p | AM / PM | AM |
%S | Seconds (00-59) | 23 |
%U | Week number of the year starting from Sunday (00-53) | 12 |
%w | Weekday number of the week | Monday (1) |
%W | Week number of the year starting from Monday (00-53) | 34 |
%x | Local date | 06/07/22 |
%X | Local time | 12:30:45 |
%y | Year (short version) | 22 |
%Y | Year (full version) | 2022 |
%z | UTC offset | +0100 |
%Z | Timezone | CST |
%% | % Character | % |
struct_time 類具有以下屬性:
Attribute | Value |
tm_year | 0000, .., 2019, …, 9999 |
tm_mon | 1-12 |
tm_mday | 1-31 |
tm_hour | 0-23 |
tm_min | 0-59 |
tm_sec | 0-61 |
tm_wday | 0-6 (Monday is 0) |
tm_yday | 1-366 |
tm_isdst | 0, 1, -1 (daylight savings time, -1 when unknown) |
現在讓我們看幾個 time 模塊的例子。
使用time模塊查找日期和時間
使用上表中描述的內置函數和格式化代碼,可以在 Python 中輕松獲取日期和時間。
Output:
datetime 模塊
與time模塊類似,datetime模塊包含處理日期和時間所必需的所有方法。
內置功能:
下表介紹了本模塊中的一些重要功能:
function | Description |
datetime() | datetime 的構造函數 |
datetime.today() | 返回當前本地日期和時間 |
datetime.now() | 返回當前本地日期和時間 |
date() | 以年、月、日為參數,創建相應的日期 |
time() | 以小時、分鐘、秒、微秒和tzinfo作為參數,并創建相應的日期 |
date.fromtimestamp() | 轉換秒數以返回相應的日期和時間 |
timedelta() | 它是不同日期或時間之間的差異(持續時間) |
使用 datetime 查找日期和時間
現在,讓我們嘗試實現這些函數,以使用datetime模塊在 Python 中查找日期和時間。
Output: