Search code examples
pythonpandastimezonepython-datetimepytz

Getting NonExistentTimeError in pytz


With this example:

import pandas as pd
import pytz

timestamp = pd.Timestamp('2023-04-30 02:20:28.594000')
timezone = pytz.timezone('Africa/Casablanca')


print(
    timestamp.tz_localize(timezone, ambiguous=True)
)

I'm getting NonExistentTimeError: 2023-04-30 02:20:28.594000.

Why is this time nonexistent? I happen to have local Casablanca data with that time.


Solution

  • Previously, it was predicted that Morocco (Africa/Casablanca) would have its "spring-forward" transition on April 30th, 2023. This was corrected in TZDB version 2023a.

    From the release announcement:

    Changes to future timestamps
    
    In 2023 Morocco's spring-forward transition after Ramadan
    will occur April 23, not April 30.  (Thanks to Milamber.)
    Adjust predictions for future years accordingly.  This affects
    predictions for 2023, 2031, 2038, and later years.
    

    The releases for pytz follow the tzdb releases. Update to the current release of pytz and the transition date should be adjusted accordingly.

    Also, note that pytz has been deprecated for a while now. In new projects consider using zoneinfo instead. Note that zoneinfo will use the time zone data present on the operating system if present (i.e., Linux, MacOS, etc.), or data from the tzdata package in other cases (Windows, embedded systems, etc.). In either case, be sure you are using the latest version.