0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

指定した期間(開始日から終了日まで)、指定した国の祝日のリストをCSVファイル形式で出力

Last updated at Posted at 2023-03-19

image.png
image.png
 画像は2023年の、アメリカの祝日と日本の祝日のCSVファイルです。このような形式でCSVファイルを作成するPythonプログラムをChatGPTに書いてもらいました。

pip install holidays

祝日情報を取得するために「holidays」というライブラリを使用します。

write_holidays_to_csv.py
import csv
from datetime import date, timedelta
import holidays

def write_holidays_to_csv(start_date, end_date, country_code, output_file):
    country_holidays = getattr(holidays, country_code)()
    current_date = start_date
    with open(output_file, 'w', newline='') as csvfile:
        fieldnames = ['Date', 'Holiday']
        writer = csv.DictWriter(csvfile, fieldnames=fieldnames)
        writer.writeheader()
        while current_date <= end_date:
            if current_date in country_holidays:
                writer.writerow({'Date': current_date.isoformat(), 'Holiday': country_holidays[current_date]})
            current_date += timedelta(days=1)

# 引数は「開始日、終了日、国コード」
write_holidays_to_csv(date(2023, 1, 1), date(2023, 12, 31), 'US', 'us_holidays_2023.csv')

国コードはISOコード(2文字)です。
https://ja.wikipedia.org/wiki/ISO_3166-1
祝日はアメリカでは州によって違いがある等を考慮する場合は注意してください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?