關于Python時間日期常見的一些操作方法
更新時間:2024年09月28日 14:15:22 作者:不在同一頻道上的呆子
Python的datetime模塊是處理日期和時間的強大工具,datetime類可以獲取當前時間、指定日期、計算時間差、訪問時間屬性及格式化時間,這些功能使得在Python中進行時間日期處理變得簡單高效,需要的朋友可以參考下
前言
在Python中,我們用于處理時間和日期相關的類型最常用的模塊是datetime模塊。該模塊提供了很多與時間日期相關的類,對我們處理時間日期變得很方便。
以下是一些常見的關于時間日期的操作。
一、datetime類
1、獲取當前日期和時間(年、月、日、時、分、秒、微秒)
from datetime import datetime
today = datetime.today()
now = datetime.now()
print("當前日期和時間是:", today) # 當前日期和時間是: 2024-07-29 21:05:42.281563
print("當前日期和時間是:", now) # 當前日期和時間是: 2024-07-29 21:05:42.2815632、 輸出指定的日期
specific_date = datetime(2024, 7, 29)
specific_date1 = datetime(2024, 7, 30, 21, 55, 00)
print("指定日期是:", specific_date) # 指定日期是: 2024-07-29 00:00:00
print("指定日期是:", specific_date1) # 指定日期是: 2024-07-30 21:55:003、計算時間差
# 兩個日期相減會得到時間差對象(timedelta) delta = specific_date1 - specific_date print(delta, type(delta)) # 1 day, 21:55:00 <class 'datetime.timedelta'> # 獲取兩個日期相差的天數和秒數 print(delta.days, delta.seconds) # 1 78900
4、訪問datetime對象的屬性
# 通過datetime對象的屬性,單獨獲取時間的年月日時分秒
year = now.year
month = now.month
day = now.day
hour = now.hour
minute = now.minute
second = now.second
print(f"年: {year}, 月: {month}, 日: {day}, 時: {hour}, 分: {minute}, 秒: {second}")
# 輸出->年: 2024, 月: 7, 日: 29, 時: 21, 分: 08, 秒: 405、格式化時間
# 格式化時間對象
formatted_datetime = now.strftime('%Y年%m月%d日 %H時%M分%S秒')
print("格式化時間:", formatted_datetime) # 2024年07月29日 21時08分19秒二、date類
date類一般用于處理日期(年、月、日)。
1、獲取當前的日期(年、月、日)和屬性
from datetime import date
today1 = date.today()
year = today1.year
month = today1.month
day = today1.day
print(today1) # 2024-07-29
print(f"年: {year}, 月: {month}, 日: {day}") # 年: 2024, 月: 7, 日: 29三、time類
time類主要用于處理時間(時、分、秒、微秒)。
1、指定時間
from datetime import time
current_time = time(15, 48, 6) # 假設當前時間是15時48分6秒
print("當前時間:", current_time) # 當前時間: 15:48:062、通過訪問time屬性分別獲取時、分、秒、微秒
precise_time = time(15, 48, 6, 123456)
print("精確時間:", precise_time)
hour = current_time.hour
minute = current_time.minute
second = current_time.second
microsecond = precise_time.microsecond
print(f"時: {hour}, 分: {minute}, 秒: {second}, 微秒: {microsecond}") # 時: 15, 分: 48, 秒: 6, 微秒: 123456四、timedelta類
1、計算過去未來的日期
from datetime import timedelta
# 計算未來三天的日期
future_date = now + timedelta(days=3)
print("三天后的日期:", future_date) # 三天后的日期: 2024-08-01 21:16:26.496122
# 計算過去一小時的時間
past_time = now - timedelta(hours=1)
print("過去1小時時間:", past_time) # 過去1小時時間:2024-07-28 20:16:26.4961222、使用多個參數創(chuàng)建timedelta對象
delta = timedelta(weeks=1, days=1, hours=1, minutes=1, seconds=1, microseconds=1)
print("時間:", delta) # 時間: 8 days, 1:01:01.000001總結
到此這篇關于Python時間日期常見的一些操作方法的文章就介紹到這了,更多相關Python時間日期操作內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

