python的datetime函數(shù)如何使用

小億
110
2024-04-08 17:39:36

Python的datetime模塊提供了處理日期和時(shí)間的功能。以下是一些常用的方法和示例:

  1. 導(dǎo)入datetime模塊:
import datetime
  1. 獲取當(dāng)前日期和時(shí)間:
now = datetime.datetime.now()
print(now)
  1. 創(chuàng)建特定日期和時(shí)間對(duì)象:
date = datetime.datetime(2021, 10, 31, 12, 30, 45)
print(date)
  1. 格式化日期和時(shí)間對(duì)象:
formatted_date = now.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date)
  1. 獲取日期和時(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)
  1. 計(jì)算日期差值:
date1 = datetime.datetime(2021, 10, 31)
date2 = datetime.datetime(2021, 11, 10)
delta = date2 - date1

print(delta.days)

這些是常用的datetime函數(shù)的用法,希望對(duì)你有幫助。

0