Python datetime模塊詳細(xì)介紹(核心模塊)
Python 的 datetime 模塊是處理日期和時(shí)間的核心庫,提供了豐富的類和方法來操作日期、時(shí)間、時(shí)間間隔和時(shí)區(qū)。以下是對(duì)該模塊的詳細(xì)介紹:
主要類
datetime.date
處理日期(年、月、日)。- 屬性:
year,month,day - 常用方法:
date.today(): 返回當(dāng)前本地日期。date.fromisoformat("YYYY-MM-DD"): 從字符串解析日期。date.replace(year, month, day): 替換日期部分。date.weekday(): 返回星期幾(0=周一, 6=周日)。date.strftime(format): 格式化日期為字符串。
- 屬性:
datetime.time
處理時(shí)間(時(shí)、分、秒、微秒)。- 屬性:
hour,minute,second,microsecond,tzinfo(時(shí)區(qū)) - 常用方法:
time.replace(hour, minute, second, microsecond): 替換時(shí)間部分。time.strftime(format): 格式化時(shí)間為字符串。
- 屬性:
datetime.datetime
處理日期和時(shí)間的組合(最常用)。- 屬性:
year,month,day,hour,minute,second,microsecond,tzinfo - 常用方法:
datetime.now(tz=None): 返回當(dāng)前本地日期時(shí)間。datetime.utcnow(): 返回當(dāng)前 UTC 時(shí)間。datetime.combine(date, time): 合并日期和時(shí)間對(duì)象。datetime.strptime(string, format): 解析字符串為日期時(shí)間。datetime.timestamp(): 轉(zhuǎn)換為 Unix 時(shí)間戳(秒)。datetime.date(): 提取日期部分。datetime.time(): 提取時(shí)間部分。datetime.strftime(format): 格式化輸出。
- 屬性:
datetime.timedelta
表示時(shí)間間隔(如天、秒、微秒)。- 用途: 計(jì)算日期/時(shí)間的加減。
- 示例:
future = datetime.now() + timedelta(days=7) # 7天后
datetime.tzinfo(抽象類)
處理時(shí)區(qū)信息,需自定義實(shí)現(xiàn)。
替代方案: 使用標(biāo)準(zhǔn)庫datetime.timezone(Python 3.2+)或第三方庫pytz。datetime.timezone
實(shí)現(xiàn)tzinfo的簡單時(shí)區(qū)類。
- 示例:
tz = timezone(timedelta(hours=8)) # UTC+8 時(shí)區(qū) dt = datetime(2023, 5, 15, tzinfo=tz)
關(guān)鍵操作示例
1. 獲取當(dāng)前時(shí)間
from datetime import datetime now = datetime.now() # 2023-05-15 14:30:45.123456
2. 時(shí)間格式化與解析
# 日期時(shí)間 → 字符串
s = now.strftime("%Y-%m-%d %H:%M:%S") # "2023-05-15 14:30:45"
# 字符串 → 日期時(shí)間
dt = datetime.strptime("2023-05-15", "%Y-%m-%d") # 時(shí)間部分默認(rèn)為 00:00:003. 時(shí)間計(jì)算
from datetime import timedelta # 加減時(shí)間 tomorrow = now + timedelta(days=1) last_hour = now - timedelta(hours=1) # 計(jì)算時(shí)間差 diff = tomorrow - now print(diff.total_seconds()) # 86400.0 秒
4. 時(shí)區(qū)處理
from datetime import timezone, timedelta # 創(chuàng)建 UTC+8 時(shí)區(qū) tz_beijing = timezone(timedelta(hours=8)) dt_local = datetime(2023, 5, 15, 14, 30, tzinfo=tz_beijing) # 轉(zhuǎn)換為 UTC 時(shí)間 dt_utc = dt_local.astimezone(timezone.utc) # 2023-05-15 06:30:00+00:00
5. 獲取日期/時(shí)間部分
date_part = now.date() # 返回 date 對(duì)象 time_part = now.time() # 返回 time 對(duì)象 year = now.year # 2023
格式化符號(hào)表
| 符號(hào) | 含義 | 示例 |
|---|---|---|
%Y | 四位年份 | 2023 |
%m | 兩位月份(01-12) | 05 |
%d | 兩位日期(01-31) | 15 |
%H | 24小時(shí)制小時(shí)(00-23) | 14 |
%M | 分鐘(00-59) | 30 |
%S | 秒(00-59) | 45 |
%f | 微秒(000000-999999) | 123456 |
%A | 星期全名 | Monday |
%a | 星期縮寫 | Mon |
%B | 月份全名 | May |
%b | 月份縮寫 | May |
最佳實(shí)踐
- 處理時(shí)區(qū):
優(yōu)先使用timezone或第三方庫pytz(支持 IANA 時(shí)區(qū)數(shù)據(jù)庫)。 - 時(shí)間存儲(chǔ):
建議用 UTC 時(shí)間存儲(chǔ),顯示時(shí)再轉(zhuǎn)換為本地時(shí)間。 - 性能敏感場景:
考慮使用time.monotonic()或time.perf_counter()替代時(shí)間差計(jì)算。
完整示例
from datetime import datetime, timedelta, timezone
# 1. 獲取當(dāng)前時(shí)間(帶時(shí)區(qū))
now = datetime.now(timezone.utc)
# 2. 轉(zhuǎn)換為北京時(shí)間 (UTC+8)
tz_beijing = timezone(timedelta(hours=8))
beijing_time = now.astimezone(tz_beijing)
# 3. 格式化輸出
formatted = beijing_time.strftime("%Y-%m-%d %H:%M:%S %Z")
print(f"Beijing Time: {formatted}") # e.g., "2023-05-15 22:30:45 UTC+08:00"
# 4. 計(jì)算7天后的日期
future = beijing_time + timedelta(days=7)
# 5. 解析字符串時(shí)間
dt_parsed = datetime.strptime("2023-12-31", "%Y-%m-%d")通過掌握 datetime 模塊,你可以高效處理絕大多數(shù)日期時(shí)間相關(guān)任務(wù)!
到此這篇關(guān)于Python datetime模塊詳解的文章就介紹到這了,更多相關(guān)Python datetime模塊內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- Python時(shí)間處理模塊time和datetime詳解
- Python中的time和datetime模塊使用方法詳解
- Python基本知識(shí)之datetime模塊詳解
- Python常用模塊之datetime模塊詳解
- python使用datetime模塊處理日期時(shí)間及常用功能詳解
- python?datetime模塊詳解
- python 常用日期處理-- datetime 模塊的使用
- python利用datetime模塊計(jì)算程序運(yùn)行時(shí)間問題
- Python Datetime模塊和Calendar模塊用法實(shí)例分析
- Python基于datetime或time模塊分別獲取當(dāng)前時(shí)間戳的方法實(shí)例
- python中datetime模塊中strftime/strptime函數(shù)的使用
相關(guān)文章
python實(shí)現(xiàn)合并兩個(gè)有序列表的示例代碼
這篇文章主要介紹了python實(shí)現(xiàn)合并兩個(gè)有序列表的示例代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2021-04-04
python之while循環(huán)、無限循環(huán)用法及說明
這篇文章主要介紹了python之while循環(huán)、無限循環(huán)用法及說明,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-06-06
Pytorch出現(xiàn)錯(cuò)誤Attribute?Error:module?‘torch‘?has?no?attrib
這篇文章主要給大家介紹了關(guān)于Pytorch出現(xiàn)錯(cuò)誤Attribute?Error:module?‘torch‘?has?no?attribute?'_six'解決的相關(guān)資料,文中通過圖文介紹的非常詳細(xì),需要的朋友可以參考下2023-11-11
淺談Pandas Series 和 Numpy array中的相同點(diǎn)
今天小編就為大家分享一篇淺談Pandas Series 和 Numpy array中的相同點(diǎn),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過來看看吧2019-06-06
selenium+python自動(dòng)化測試之鼠標(biāo)和鍵盤事件
這篇文章主要介紹了selenium+python自動(dòng)化測試之鼠標(biāo)和鍵盤事件,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧2019-01-01
python+tkinter實(shí)現(xiàn)一個(gè)簡單的秒鐘
這篇文章主要為大家詳細(xì)介紹了Python如何利用tkinter實(shí)現(xiàn)一個(gè)簡單的秒鐘,文中的示例代碼講解詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴可以自己動(dòng)手嘗試一下2024-02-02

