Skip to content

Conversation

daram62
Copy link

@daram62 daram62 commented Oct 13, 2025

Enhance error messages when ZoneInfo cannot find timezone data by providing clear,
actionable guidance using PEP-678 exception notes.

Changes

1. Enhanced ImportError handling in Lib/zoneinfo/_common.py:

  • Separate ImportError from other exceptions to provide specific guidance
  • Use PEP-678 add_note() for better error message formatting
  • Add gating logic to detect if tzdata is actually missing vs. incorrect timezone key
  • Provide different messages based on the actual cause:
    • If tzdata is not installed: suggests installation with pip
    • If tzdata is installed but key is wrong: suggests verifying the key
  • Link to official documentation for more information

2. Improvements based on code review:

  • Changed "e.g." to "for example" per Python Docs style guide
  • Used hyphens instead of unicode bullet points for better compatibility
  • Removed confusing "OS timezone data" message that was unclear for Windows users
  • Fixed NEWS filename to use gh-issue-140039 format

Example

Before:

>>> from zoneinfo import ZoneInfo
>>> z = ZoneInfo('America/New_York')
Traceback (most recent call last):
  ...
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key America/New_York'

After (when tzdata is not installed):

>>> from zoneinfo import ZoneInfo
>>> z = ZoneInfo('America/New_York')
Traceback (most recent call last):
  ...
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key America/New_York'
This error may occur if timezone data is not available. To resolve this:
  - Install the tzdata package: python -m pip install tzdata
  - Verify the timezone key is correct (for example, 'America/New_York')

For more information, see:
https://docs.python.org/3/library/zoneinfo.html

After (when tzdata is installed but key is wrong):

>>> from zoneinfo import ZoneInfo
>>> z = ZoneInfo('Invalid/Timezone')
Traceback (most recent call last):
  ...
zoneinfo._common.ZoneInfoNotFoundError: 'No time zone found with key Invalid/Timezone'
The timezone key 'Invalid/Timezone' was not found in the tzdata package.
Please verify the timezone key is correct (for example, 'America/New_York').

Testing

  • ✅ All existing tests pass (254 tests, 28 skipped)
  • ✅ Manually verified improved error message formatting with PEP-678 notes
  • ✅ Tested both scenarios: missing tzdata and incorrect timezone key
  • ✅ Verified messages display correctly in tracebacks
  • ✅ No breaking changes to API or behavior

Related Issue

Closes #140039

…sing

Add more helpful error messages when ZoneInfo cannot find timezone data,
specifically when the ImportError occurs due to missing tzdata package.

The new error message provides:
- Clear explanation of why the error occurred
- Step-by-step instructions to resolve the issue
- Link to official documentation for more information

Also override __str__ in ZoneInfoNotFoundError to properly display
multi-line error messages (KeyError wraps messages in repr() by default).

This improves user experience by making it immediately clear what went
wrong and how to fix it, rather than just stating the key wasn't found.
@daram62 daram62 requested a review from pganssle as a code owner October 13, 2025 12:35
@python-cla-bot
Copy link

python-cla-bot bot commented Oct 13, 2025

All commit authors signed the Contributor License Agreement.

CLA signed

@bedevere-app
Copy link

bedevere-app bot commented Oct 13, 2025

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

Copy link
Member

@StanFromIreland StanFromIreland left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Some comments

@bedevere-app
Copy link

bedevere-app bot commented Oct 13, 2025

Most changes to Python require a NEWS entry. Add one using the blurb_it web app or the blurb command-line tool.

If this change has little impact on Python users, wait for a maintainer to apply the skip news label instead.

This commit enhances the error messages when a timezone key is not found
in the zoneinfo module by using PEP-678 exception notes to provide clear,
actionable guidance to users.

Key improvements:
- Uses PEP-678 add_note() for better error message formatting
- Checks if tzdata package is actually missing before suggesting installation
- Provides different messages for missing tzdata vs incorrect timezone keys
- Uses hyphens instead of unicode bullet points for better compatibility
- Changes 'e.g.' to 'for example' for clarity
- Removes OS timezone data message that was confusing for Windows users

The error message now intelligently detects whether:
1. tzdata is not installed (suggests: pip install tzdata)
2. tzdata is installed but key is wrong (suggests: verify the key)

This makes debugging timezone issues much easier for Python developers.
@daram62 daram62 force-pushed the improve-zoneinfo-error-message branch from 0ff2283 to bad8647 Compare October 13, 2025 13:32
@StanFromIreland
Copy link
Member

Please do not use the Update Branch button unless necessary (e.g. fixing conflicts, jogging the CI, or very old PRs) as it uses valuable resources. For more information see the devguide.

Also, please do not force push, it makes reviewing more difficult.

@daram62
Copy link
Author

daram62 commented Oct 13, 2025

Sorry about the force push! I'm new to CPython contribution and wasn't aware of this guideline. 🥲
I'll make sure to add new commits instead of amending from now on. Thanks for letting me know!

- Change 'To resolve this:' to 'Try:' to avoid implying guaranteed solution
- Remove else block as ZoneInfoNotFoundError is clear enough without extra notes
- Simplify message structure for better readability
@LamentXU123
Copy link
Contributor

LamentXU123 commented Oct 15, 2025

Would it be better if we add detailed message to some other errors except ImportError. e.g. adding a specific error message for UnicodeEncodeError (Zone not found because of unicode errors) sounds good to me either, since it's hard to debug it when the error is actually caused by unicode errors not file-related problems. (If yes I think I can work on a seperate PR). see #140145

# If package_name doesn't exist, it means tzdata is not installed
# or there's an error in the folder name like Amrica/New_York
exc = ZoneInfoNotFoundError(f"No time zone found with key {key}")

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

also delete the tab spaces to pass the CI lint test here and line 34.

@daram62
Copy link
Author

daram62 commented Oct 15, 2025

Sounds good!! Thanks for the quick follow-up
Handling UnicodeEncodeError separately makes sense since it's a different issue from missing tzdata.

Comment on lines +27 to +33
exc.add_note("This error may occur if timezone data is not available.")
exc.add_note("Try:")
exc.add_note(" - Installing the tzdata package: python -m pip install tzdata")
exc.add_note(" - Verifying the timezone key is correct (for example, 'America/New_York')")
exc.add_note("")
exc.add_note("For more information, see:")
exc.add_note("https://docs.python.org/3/library/zoneinfo.html")
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Shouldn't we just add one note with a multiline string?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Improve error message in zoneinfo module when tzdata is missing

4 participants