Search code examples
pythondatetimetimezonepython-dateutil

Python: How to check if date is ambiguous?


Is there any simple way, how to determine if date in a datetime object is ambiguous - meaning that particular datetime could exist twice in a particular timezone in order of regular time change?

Here is an example of ambiguous datetime object. In New York timezone, on 5th November 2017 2 AM, time was shifted back to 1 AM.

import datetime
import dateutil

# definition of time zone
eastern_time = dateutil.tz.gettz('America/New_York')

# definition of ambiguous datetime object
dt = datetime.datetime(2017, 11, 5, 1, 30, 0, tzinfo=eastern_time)

I expect something like this.

>>> suggested_module.is_dt_ambiguous(dt)
True

Solution

  • You're looking for the datetime_ambiguous function, which applies during a backward transition (such as end of DST in the fall).

    dateutil.tz.datetime_ambiguous(dt, eastern_time)
    

    You might also be interested in datetime_exists, which applies during a forward transition (such as start of DST in the spring).