使用Python取得年份和星期幾的月份

WBOY
發布: 2023-09-15 17:41:02
轉載
818 人瀏覽過

使用Python取得年份和星期幾的月份

處理時間是任何日常活動中最重要的方面之一。在本文中,我們將討論如何使用 Python 從年份和工作日獲取月份。我們將利用Python 的兩個最受歡迎的庫,即calendar 和datetime,來處理月份、年份等。這兩個庫都提供了幾種處理時間的內建方法。如果我們處理這樣的函式庫,我們不需要專門關心像閏年這樣具有挑戰性的任務。

使用日曆庫

Python 中的日曆庫提供了處理日曆和日期的有用函數和類別。它提供了一系列功能來產生日曆、操作日期和執行與日曆相關的計算。它簡化了與生成日曆、計算工作日和操作日期相關的任務,使其成為處理各種應用程式中與日曆相關的操作的寶貴工具。

範例

在下面的範例中,我們首先在程式碼中匯入了日曆模組。接下來,我們定義了一個函數,它將年份和工作日分別作為整數和字串。我們迭代了 12 次,並且在每次迭代下,我們使用 weekday 方法訪問工作日的第一天。接下來,我們檢查該月的第一天,等於給定的工作日。我們返回了相應的月份。

import calendar
def get_month(year, weekday):
    for month in range(1, 13):
        _, days = calendar.monthrange(year, month)
        first_day_weekday = calendar.weekday(year, month, 1)
        if calendar.day_name[first_day_weekday] == weekday:
            return calendar.month_name[month]
    return None
year = 2023
weekday = 'Monday'
month = get_month(year, weekday)
if month:
    print(f"The month with {weekday}s as the first weekday in {year} is {month}.")
else:
    print(f"There is no {weekday} as the first weekday in any month of {year}.")
登入後複製

輸出

The month with Mondays as the first weekday in 2023 is May.
登入後複製

使用 Datetime 和 Timedelta 模組

Python 中的 timedelta 模組提供了處理時間差或持續時間的功能。它允許您對日期和時間執行算術運算,例如添加或減去時間間隔。由於時間與整數相比是不同的類型,因此普通操作不適用於它們。

範例

在下面的程式碼中,我們首先導入了 datetime 和 timedelta 模組。接下來,我們建立了一個名為 get_month 的使用者定義函數。此函數以年份和工作日作為參數。我們從 1 迭代到 13(排除 13)。在每次迭代下,程式碼都會將first_day 的工作日與傳遞給函數的工作日參數進行比較。它透過在first_day 上呼叫 strftime('%A') 方法將日期格式設為完整的工作日名稱(例如星期一、星期二等)來實現此目的。

from datetime import datetime, timedelta

def get_month(year, weekday):
    for month in range(1, 13):
        first_day = datetime(year, month, 1)
        if first_day.strftime('%A') == weekday:
            return first_day.strftime('%B')
year = 2023
weekday = 'Saturday'
month = get_month(year, weekday)
if month:
    print(f"The month with {weekday}s as the first weekday in {year} is {month}.")
else:
    print(f"There is no {weekday} as the first weekday in any month of {year}.")
登入後複製

輸出

The month with Saturdays as the first weekday in 2023 is April.
登入後複製

使用工作日方法

weekday() 方法是 Python 中 datetime 模組中的一個函數。我們用它來決定工作日。此方法傳回一個表示工作日的整數,其中星期一為 0,星期日為 6。透過對 datetime.date 物件呼叫 weekday() 方法,您可以輕鬆檢索工作日資訊並將其用於各種與日期相關的計算和Python 程式中的操作。

範例

在給定的範例中,函數 find_month_with_weekday 方法採用兩個參數:year(年份)和 weekday。它使用範圍從 1 到 13 的 for 迴圈迭代給定年份中的每個月。它使用 .weekday() 方法檢查 first_day 的工作日是否與指定的工作日匹配,該方法會傳回表示工作日的整數。這裡星期一用 0 表示,星期二用 1 表示,依此類推。如果找到符合項,它將使用 .strftime("%B") 傳回first_day 的月份名稱,這會將日期格式化為完整的月份名稱。

import datetime

def find_month_with_weekday(year, weekday):
    for month in range(1, 13):
        first_day = datetime.date(year, month, 1)
        if first_day.weekday() == weekday:
            return first_day.strftime("%B")
    return None
test_year = 2023
test_weekday = 3 
result = find_month_with_weekday(test_year, test_weekday)
if result:
    print(f"The month with {datetime.date(test_year, 1, 1 + test_weekday).strftime('%A')} as the first weekday in {test_year} is {result}.")
else:
    print(f"No month with {datetime.date(test_year, 1, 1 + test_weekday).strftime('%A')} as the first weekday found in {test_year}.")
登入後複製

輸出

The month with Wednesday as the first weekday in 2023 is June.
登入後複製

結論

在本文中,我們學習如何使用 Python 取得一年中的月份和工作日。 Python為我們提供了幾個用於時間的函式庫,如日期時間、日曆等。它還使我們能夠輕鬆處理週、月等。因此,我們可以使用這些函式庫和其他Python邏輯的組合來存取從一年到一年的月份。工作日。

以上是使用Python取得年份和星期幾的月份的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:tutorialspoint.com
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!