共計(jì) 559 個(gè)字符,預(yù)計(jì)需要花費(fèi) 2 分鐘才能閱讀完成。
Python 的 datetime 模塊提供了處理日期和時(shí)間的功能。以下是一些常用的方法和示例:
- 導(dǎo)入 datetime 模塊:
import datetime
- 獲取當(dāng)前日期和時(shí)間:
now = datetime.datetime.now()
print(now)
- 創(chuàng)建特定日期和時(shí)間對(duì)象:
date = datetime.datetime(2021, 10, 31, 12, 30, 45)
print(date)
- 格式化日期和時(shí)間對(duì)象:
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)
- 獲取日期和時(shí)間的各個(gè)部分:
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
print(year, month, day, hour, minute, second)
- 計(jì)算日期差值:
date1 = datetime.datetime(2021, 10, 31)
date2 = datetime.datetime(2021, 11, 10)
delta = date2 - date1
print(delta.days)
這些是常用的 datetime 函數(shù)的用法,希望對(duì)你有幫助。
丸趣 TV 網(wǎng) – 提供最優(yōu)質(zhì)的資源集合!
正文完