Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fixing timezone-aware datetime handling #22

Closed
wants to merge 2 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 13 additions & 4 deletions humanize/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,15 +3,23 @@

"""Time humanizing functions. These are largely borrowed from Django's
``contrib.humanize``."""

import time
from pytz import utc
from datetime import datetime, timedelta, date
from .i18n import ngettext, gettext as _

__all__ = ['naturaldelta', 'naturaltime', 'naturalday', 'naturaldate']

def _now():
return datetime.now()
return utc.localize(datetime.utcnow())

def convert_to_utc(value):
if isinstance(value, datetime):
if value.tzinfo:
return value.astimezone(utc)
else:
return utc.localize(value)
else:
return value

def abs_timedelta(delta):
"""Returns an "absolute" value for a timedelta, always representing a
Expand All @@ -24,6 +32,7 @@ def abs_timedelta(delta):
def date_and_delta(value):
"""Turn a value into a date and a timedelta which represents how long ago
it was. If that's not possible, return (None, value)."""
value = convert_to_utc(value)
now = _now()
if isinstance(value, datetime):
date = value
Expand All @@ -46,7 +55,6 @@ def naturaldelta(value, months=True):
``naturaltime``, but does not add tense to the result. If ``months``
is True, then a number of months (based on 30.5 days) will be used
for fuzziness between years."""
now = _now()
date, delta = date_and_delta(value)
if date is None:
return value
Expand Down Expand Up @@ -112,6 +120,7 @@ def naturaltime(value, future=False, months=True):
datetimes, where the tense is always figured out based on the current time.
If an integer is passed, the return value will be past tense by default,
unless ``future`` is set to True."""

now = _now()
date, delta = date_and_delta(value)
if date is None:
Expand Down
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@
test_suite="tests",
tests_require=['mock'],
install_requires=[
# -*- Extra requirements: -*-
'pytz'
],
entry_points="""
# -*- Entry points: -*-
Expand Down
Loading