Skip to content

TypeError: can't subtract offset-naive and offset-aware datetimes #122

@ErikKalkoken

Description

@ErikKalkoken

What did you do?

I wanted to calculate naturaltime between two timezone aware datatimes.

What did you expect to happen?

Get a string the with naturaltime between those datetimes.

What actually happened?

A TypeError exception was raised:

Traceback (most recent call last):
  File "/home/erik/python/projects/aa-dev/aa-memberaudit/temp/humanize_bug.py", line 8, in <module>
    result = humanize.naturaltime(same_dt, when=my_now)
  File "/home/erik/python/projects/aa-dev/venv/lib/python3.10/site-packages/humanize/time.py", line 253, in naturaltime
    date, delta = _date_and_delta(value, now=now)
  File "/home/erik/python/projects/aa-dev/venv/lib/python3.10/site-packages/humanize/time.py", line 76, in _date_and_delta
    delta = now - value
TypeError: can't subtract offset-naive and offset-aware datetimes

What versions are you using?

  • OS: Ubuntu 22.04.2
  • Python: 3.10
  • Humanize: 4.7.0

Please include code that reproduces the issue.

The best reproductions are self-contained scripts with minimal dependencies.

import datetime as dt

import humanize

my_now = dt.datetime.now(tz=dt.timezone.utc)
same_dt = my_now - dt.timedelta(days=3, hours=1)

result = humanize.naturaltime(same_dt, when=my_now)

Additional information

This bug was introduced with 4.7, the code works fine with 4.6.

As a workaround one could remove the when=my_now part (a workaround to get it the function working with aware datetimes), but then it no longer works with humanize < 4.7, which would make 4.7 a breaking change. And it would also not work for when when is used in any other way.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions