iT邦幫忙

2024 iThome 鐵人賽

DAY 5
0
Python

30 天學會用 Python pandas 和 openpyxl 處理 Excel —— 成為用 Python 處理 Excel 檔案的高手系列 第 5

Python 如何找到未來三個月的起迄日期?【Python 處理 Excel #5】

  • 分享至 

  • xImage
  •  

本篇文章同步發布於 Python 如何找到未來三個月的起迄日期?【Python 處理 Excel #5】

前言

講一個和 pandas 本身關聯較小,但處理資料時一定會遇到的問題:要怎麼針對日期判斷月份?例如公司系統上有所有的訂單資料,可是只想要交貨日期在在這個月、下個月和下下個月的訂單資料怎麼處理?這篇文章介紹如何用 datatime 找到未來三個月的起迄日期,後續的文章再介紹如何篩選出未來三個月的資料


如何找到當前月的第一天?

現在時間是 2024 年 9 月,以下例子介紹如何使用 Python datetime 模組找到這個月的第一天,也就是 2024 年 9 月 1 日。

from datetime import datetime

# 獲取當前日期和時間
current_date = datetime.now()

# 使用 replace() 方法找到當前月份的第一天
first_day_of_current_month = current_date.replace(day=1, hour=0, minute=0, second=0)

print(f"這個月的第一天是: {first_day_of_current_month}")

解釋

datetime 模組中導入 datetime 類別。接著使用 datetime.now() 獲取當前的日期和時間,並使用 replace() 方法,將 current_dateday 設置為 1,這樣就能得到當前月的第一天。這裡將 hourminutesecond 設置為 0,避免精確度差異造成比較或計算日期時影響結果,有時候甚至會將微秒 (microsecond) 也設定為 0。


如何找到當前月的最後一天?

以下使用 datetime.now()calendar.monthrange() 找到當前月的最後一天。

from datetime import datetime
import calendar

# 獲取當前日期和時間,並將微秒設置為 0
current_date = datetime.now().replace(microsecond=0)

# 獲取當前月份的最後一天
_, last_day = calendar.monthrange(current_date.year, current_date.month)

# 使用 replace() 方法找到當前月份的最後一天
last_day_of_current_month = current_date.replace(day=last_day, hour=23, minute=59, second=59)

print(f"這個月的最後一天是: {last_day_of_current_month.date()}")
print(f"最後一天的時間是: {last_day_of_current_month}")

解釋

calendar.monthrange 是 Python 的 calendar 模組中的一個函數,用於獲取指定年份和月份的第一天是星期幾以及該月份的天數。這個函數的返回值是一個元組 (tuple),包含兩個整數:第一個整數表示該月份的第一天是星期幾,第二個整數表示該月份的總天數。在這裡將 tuple 的第二個元素賦值給 last_day 變數。

接著使用 replace() 方法將 current_dateday 設置為 last_day,並將 hourminutesecond 設置為 23、59 和 59,這樣就得到了當前月份的最後一天的時間。


如何找到下個月的第一天?

上面的例子再加上 timedelta 找到下個月的第一天。

from datetime import datetime, timedelta
import calendar

# 獲取當前日期和時間,並將微秒設置為 0
current_date = datetime.now().replace(microsecond=0)

# 獲取當前月份的最後一天
_, last_day = calendar.monthrange(current_date.year, current_date.month)
last_day_of_current_month = current_date.replace(day=last_day, hour=23, minute=59, second=59)

# 下個月的第一天
first_day_of_next_month = last_day_of_current_month + timedelta(days=1)
first_day_of_next_month = first_day_of_next_month.replace(hour=0, minute=0, second=0)

print(f"下個月的第一天是: {first_day_of_next_month.date()}")

解釋

timedelta 是 Python datetime 模組中的一個類別,用於表示時間間隔或兩個時間點之間的差異。它可以用來進行日期和時間的加減運算。使用 timedelta(days=1)last_day_of_current_month 加上一天,得到下個月的第一天。最後使用 replace() 方法將時間設置為 00:00:00。


如何找到未來三個月的起迄日期?

我們可以利用 Python 的 replace()calendar.monthrange()timedelta() 方法的組合得到未來三個月的日期,概念如下:

  • 獲取當前日期:使用 datetime.now() 獲取當前的日期和時間,並將微秒部分設置為 0,以簡化時間的表示。
  • 計算當前月份的最後一天:使用 calendar.monthrange(current_date.year, current_date.month) 獲取當前月份的天數,這樣可以得到當前月的最後一天。
  • 計算下個月的第一天:將當前月份的最後一天加上一天,這樣就可以得到下個月的第一天。然後使用 replace() 方法將時間設置為 00:00:00,這樣就得到了下個月的第一天。
  • 重複計算未來的日期:重複以上步驟三次,以計算未來三個月的第一天。每次計算下個月的第一天時,使用上一個月的最後一天來進行計算,這樣可以確保每個月份的天數都得到正確處理。

這種方法的優點在於能自動考慮每個月份的具體天數,包括 28 天的二月、30 天的月份以及 31 天的月份,並且能夠正確處理閏年等特殊情況。


何時需要未來三個月的日期範圍?

在某些情況下,我們可能需要針對未來三個月的資料進行分析。例如,當我們希望預測未來的訂單需求或評估生產計劃時,就需要準確地找到未來三個月的日期範圍。之後介紹 pandas 篩選的文章會提到如何篩選未來三個月的資料,以便針對特定的需求進行分析。


總結

  • 這篇介紹如何使用 Python 的 datetime 模組來獲取當前月份的第一天和最後一天,以及下個月的第一天。
  • 透過結合 replace()calendar.monthrange()timedelta() 方法,可以計算未來三個月的起迄日期。

本篇文章同步發布於 Python 如何找到未來三個月的起迄日期?【Python 處理 Excel #5】


上一篇
Python pandas 增加 DataFrame 欄位以及 apply 用法【Python 處理 Excel #4】
下一篇
Python pandas 缺失值介紹:NaN 和 NaT【Python 處理 Excel #6】
系列文
30 天學會用 Python pandas 和 openpyxl 處理 Excel —— 成為用 Python 處理 Excel 檔案的高手27
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言