Skip to content

groupby with daily frequency fails with NonExistentTimeError on clock change day in Brazil #23742

Closed
@pierremoulinier

Description

@pierremoulinier

Code Sample

import pandas as pd
idx = pd.date_range(start='2017-10-10', end='2017-10-20', freq='1H')
idx = idx.tz_localize('UTC').tz_convert('America/Sao_Paulo')
df = pd.DataFrame(data=list(range(len(idx))), index=idx)
groups = df.groupby(pd.Grouper(freq='1D'))

Problem description

This code raises NonExistentTimeError

The root cause of the problem seems to be that pandas assumes that all days start at midnight local time, which is not the case in Sao Paulo on short clock-change days (the local canonical time goes from 23:59 on Oct 14 to 01:00 on Oct 15). The grouper tries to build a tz-aware object for 2017-10-15 00:00 which is not a valid "canonical" local time in Sao Paulo. This results in an exception being raised.

This is of course a problem when I want to aggregate daily values based on 'Sao Paulo days'.

A possible workaround is to write a custom grouper that will build the first timestamp of the day by using helper functions such as pytz.normalize or dateutil.tz.resolve_imaginary.

However using a custom python function for grouping significantly degrades grouping performance.

Expected Output

This should not raise an exception, it should return valid pandas group by objects. On the clock-change day, all timestamps from 2017-10-15 01:00 to 2017-10-15 23:59 local time should be grouped together and the timestamp associated with that group should be a tz-aware object representing 2017-10-15 01:00 local time.

Output of pd.show_versions()

INSTALLED VERSIONS

commit: None
python: 3.6.5.final.0
python-bits: 64
OS: Linux
OS-release: 4.4.0-17134-Microsoft
machine: x86_64
processor: x86_64
byteorder: little
LC_ALL: None
LANG: C.UTF-8
LOCALE: en_US.UTF-8

pandas: 0.22.0
pytest: None
pip: None
setuptools: 39.0.1
Cython: None
numpy: 1.13.3
scipy: 0.19.1
pyarrow: None
xarray: None
IPython: 5.5.0
sphinx: None
patsy: None
dateutil: 2.6.1
pytz: 2018.3
blosc: None
bottleneck: None
tables: 3.4.2
numexpr: 2.6.4
feather: None
matplotlib: 2.1.1
openpyxl: None
xlrd: None
xlwt: None
xlsxwriter: None
lxml: None
bs4: 4.6.0
html5lib: 0.999999999
sqlalchemy: None
pymysql: None
psycopg2: None
jinja2: 2.10
s3fs: None
fastparquet: None
pandas_gbq: None
pandas_datareader: None

Metadata

Metadata

Assignees

No one assigned

    Labels

    DatetimeDatetime data dtypeReshapingConcat, Merge/Join, Stack/Unstack, ExplodeTestingpandas testing functions or related to the test suite

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions