Skip to content

Commit

Permalink
Add support for Local Time
Browse files Browse the repository at this point in the history
  • Loading branch information
nicoe committed Jun 2, 2017
1 parent b3abd4c commit 4eac016
Show file tree
Hide file tree
Showing 3 changed files with 26 additions and 1 deletion.
9 changes: 9 additions & 0 deletions examples/example-v0.4.0.toml
Original file line number Diff line number Diff line change
Expand Up @@ -175,6 +175,15 @@ key2 = 1979-05-27T00:32:00-07:00
key3 = 1979-05-27T00:32:00.999999-07:00


################################################################################
## Time

# Time is only the time portion of an RFC 3339 date.

lt1 = 07:32:00
lt2 = 00:32:00.999999


################################################################################
## Array

Expand Down
4 changes: 3 additions & 1 deletion tests/decoding_test.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
"""Decodes toml and outputs it as tagged JSON"""
"""Decodes toml and outputs it as tagged JSON"""

import datetime
import json
Expand Down Expand Up @@ -46,6 +46,8 @@ def tag(value):
elif isinstance(value, datetime.datetime):
sdate = value.strftime('%Y-%m-%dT%H:%M:%SZ')
return {'type': 'datetime', 'value': sdate}
elif isinstance(value, datetime.time):
return {'type': 'time', 'value': value.strftime('%H:%M:%S.%f')}
assert False, 'Unknown type: %s' % type(value)


Expand Down
14 changes: 14 additions & 0 deletions toml.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@
__version__ = "0.9.2"
__spec__ = "0.4.0"

TIME_RE = re.compile("(\d{2}):(\d{2}):(\d{2})(\.(\d{3,6}))?", re.ASCII)

class TomlDecodeError(Exception):
pass

Expand Down Expand Up @@ -590,6 +592,10 @@ def _load_value(v, _dict, strictly_valid=True):
inline_object = _get_empty_inline_table(_dict)
_load_inline_object(v, inline_object, _dict)
return (inline_object, "inline_object")
elif TIME_RE.match(v):
h, m, s, _, ms = TIME_RE.match(v).groups()
time = datetime.time(int(h), int(m), int(s), int(ms) if ms else 0)
return (time, "time")
else:
parsed_date = _load_date(v)
if parsed_date is not None:
Expand Down Expand Up @@ -817,6 +823,7 @@ def _dump_value(v):
bool: lambda: str(v).lower(),
float: lambda: _dump_float(v),
datetime.datetime: lambda: v.isoformat()[:19]+'Z',
datetime.time: lambda: _dump_time(v),
}
# Lookup function corresponding to v's type
dump_fn = dump_funcs.get(type(v))
Expand Down Expand Up @@ -854,3 +861,10 @@ def _dump_list(v):

def _dump_float(v):
return "{0:.16g}".format(v).replace("e+0", "e+").replace("e-0", "e-")

def _dump_time(v):
utcoffset = v.utcoffset()
if utcoffset is None:
return v.isoformat()
# The TOML norm specifies that it's local time thus we drop the offset
return v.isoformat()[:-6]

0 comments on commit 4eac016

Please sign in to comment.