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

* time.py, added iso 8601 support #130

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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: 17 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -103,6 +103,23 @@ python3 -m pip install -e .
'an hour ago'
```

#### Also accepts iso8601 text strings

```pycon
>>> import humanize
>>> humanize.naturaldate('2007-06-05')
'Jun 05 2007'
>>> humanize.naturaldate('2007-06-05T22:00:10')
'Jun 05 2007'
>>> humanize.naturaldate('2007-06-05T22:00:10+02:00')
'Jun 05 2007'
>>> humanize.naturaltime('22:00:10') # run at 22:00:00
'10 seconds from now'

Relies on the native `fromisoformat` function that exists on date, datetime and time objects.
```
Comment on lines +116 to +118
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Please can you move the final triple backticks after '10 seconds from now'?

They indicate where the special code formatting ends.

For example, right now it looks like:

image

https://github.com/velle/humanize/blob/iso8601/README.md#also-accepts-iso8601-text-strings



### Precise time delta

```pycon
Expand Down
46 changes: 46 additions & 0 deletions src/humanize/time.py
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,47 @@ def _now() -> dt.datetime:
return dt.datetime.now()


def _parseiso(
velle marked this conversation as resolved.
Show resolved Hide resolved
value: dt.time | dt.date | dt.datetime | float | str,
) -> dt.time | dt.date | dt.datetime | float | str:
"""If string attempts to parse as iso8601 into date, datetime or time.

Args:
value (str or any object): String to be parsed.

Returns:
str (str or any): If string, it will attempt parsing as
datetime.date, datetime.datetime or datetime.time, in that order,
and return the result of the first succesful parsing, if any.

Parsing is attempted with the iso8601 function for each of the classes.

If `value` is not a string or if all attempts at parsing fail,
`value` is returned as is.

"""
if isinstance(value, str):
try:
# catches eg '2023-04-01'
return dt.date.fromisoformat(value)
except ValueError:
pass

try:
# catches eg '2023-04-01T12:00:00.123456+02:00', '2023-04-20 12:00:00'
return dt.datetime.fromisoformat(value)
except ValueError:
pass

try:
# catches eg '20:00', '20:00:16.123456', 'T20:00Z'
return dt.time.fromisoformat(value)
except ValueError:
pass

return value


def _abs_timedelta(delta: dt.timedelta) -> dt.timedelta:
"""Return an "absolute" value for a timedelta, always representing a time distance.

Expand Down Expand Up @@ -246,6 +287,7 @@ def naturaltime(
str: A natural representation of the input in a resolution that makes sense.
"""
now = when or _now()
value = _parseiso(value)

if isinstance(value, dt.datetime) and value.tzinfo is not None:
value = dt.datetime.fromtimestamp(value.timestamp())
Expand Down Expand Up @@ -274,6 +316,8 @@ def naturalday(value: dt.date | dt.datetime, format: str = "%b %d") -> str:
formatted according to `format`.

"""
value = _parseiso(value)

try:
value = dt.date(value.year, value.month, value.day)
except AttributeError:
Expand All @@ -298,6 +342,8 @@ def naturalday(value: dt.date | dt.datetime, format: str = "%b %d") -> str:

def naturaldate(value: dt.date | dt.datetime) -> str:
"""Like `naturalday`, but append a year for dates more than ~five months away."""
value = _parseiso(value)

try:
value = dt.date(value.year, value.month, value.day)
except AttributeError:
Expand Down
Loading