Skip to content

[Bug]: Matplotlib date2num timezone removal issue #27879

@DStauffman

Description

@DStauffman

Bug summary

There is a problem if some dates have time zone information and some are just dates and not datetimes. In date2num, only the first occurence in the list is checked, but plain dates cannot be converted. tzi = getattr(d[0], 'tzinfo', None)

Code for reproduction

>> import datetime
>> from matplotlib.dates import date2num

>> date2num([datetime.date(2024, 3, 5), datetime.datetime(2024, 3, 4, tzinfo=datetime.UTC)])
array([19787., 19786.])

>> date2num([datetime.datetime(2024, 3, 4, tzinfo=None), datetime.date(2024, 3, 5)])
array([19786., 19787.])

>> date2num([datetime.datetime(2024, 3, 4, tzinfo=datetime.UTC), datetime.date(2024, 3, 5)])
# Expected array([19787., 197876.]), got error instead


### Actual outcome

File ...\Lib\site-packages\matplotlib\dates.py:459 in date2num
d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d]

File ...\Lib\site-packages\matplotlib\dates.py:459 in
d = [dt.astimezone(UTC).replace(tzinfo=None) for dt in d]

AttributeError: 'datetime.date' object has no attribute 'astimezone'


### Expected outcome

Expected `array([19787., 197876.])`

### Additional information

Not sure if this is a valid use case or not, but the bug is triggered if the first item in the list is time zone aware, and then any other item is just a datetime.date and not a datetime.datetime

### Operating system

Windows 10

### Matplotlib Version

3.8.2

### Matplotlib Backend

QtAgg

### Python version

3.11.5

### Jupyter version

_No response_

### Installation

pip

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions