Workalendar库:实现ISO代码与地区英文名称互转并导出子地区对应关系至CSV以兼容英文导入逻辑
Got it, let's break this down to solve your problem fully—we'll get the subregion ISO-code-to-name mappings saved to CSV, and make sure everything works with the import pattern you're using from the docs.
Step 1: Extract and Save Subregion Mappings
First, we'll pull the full registry including subregions, then capture each entry's ISO code, human-readable name, and even the module path (which will help with dynamic imports later). Here's the code:
from workalendar.registry import registry import pandas as pd # Fetch all calendars, including subregions all_regions = registry.get_calendars(include_subregions=True) # Build a list of mappings with all relevant info region_data = [] for iso_code, calendar_cls in all_regions.items(): region_data.append({ "iso_code": iso_code, "english_name": calendar_cls.name, "import_module": calendar_cls.__module__ # Helps with dynamic imports }) # Convert to DataFrame and save to CSV df_regions = pd.DataFrame(region_data) df_regions.to_csv("./holiday_region_mappings.csv", index=False)
Your CSV will have three columns:
iso_code: The ISO shorthand (e.g.,FR-IDFfor Île-de-France)english_name: The official English name of the regionimport_module: The module path you'd use to import the calendar class (e.g.,workalendar.europe.france)
Step 2: Reverse Lookup (Name to ISO Code)
If you need to go from an English name back to its ISO code, you can create a quick lookup dictionary from the registry:
# Create a name-to-ISO-code dictionary name_to_iso = {cls.name: code for code, cls in all_regions.items()} # Example: Get ISO code for "Texas" print(name_to_iso["Texas"]) # Outputs: US-TX
Step 3: Compatibility with the Official Import Pattern
To match the docs' approach of importing by region name (like from workalendar.europe import France), you can use the import_module field to dynamically import the class without hardcoding paths:
import importlib from datetime import date # Let's use the "Île-de-France" calendar as an example target_region_name = "Île-de-France" # Get the corresponding calendar class from the registry calendar_cls = all_regions[name_to_iso[target_region_name]] # Alternatively, import dynamically using the module path # module = importlib.import_module(calendar_cls.__module__) # calendar_cls = getattr(module, calendar_cls.__name__) # Use the calendar exactly like the official example cal = calendar_cls() print(cal.find_following_working_day(date(2018, 7, 6))) # Outputs: datetime.date(2018, 7, 6)
This way, you can easily switch between ISO codes and English names while keeping full compatibility with Workalendar's standard usage.
内容的提问来源于stack exchange,提问作者user10443249

