Skip to content

Commit

Permalink
Serialize dates in structured data (#37)
Browse files Browse the repository at this point in the history
  • Loading branch information
vsalvino authored Jun 28, 2022
1 parent 1bda046 commit dcadbc9
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 3 deletions.
4 changes: 4 additions & 0 deletions docs/releases.rst
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ Release Notes

* Check for empty site when getting site name.

* Support serializing ``datetime.date`` objects in structured data.


2.0.0
-----
Expand All @@ -29,6 +31,8 @@ Release Notes

* Check for empty site when getting site name.

* Support serializing ``datetime.date`` objects in structured data.


1.0.0
-----
Expand Down
10 changes: 7 additions & 3 deletions wagtailseo/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import re
from datetime import datetime, time
from datetime import date, datetime, time
from json import JSONEncoder
from typing import List, Union

Expand All @@ -13,12 +13,12 @@
MEDIA_IS_ABSOLUTE = PROTOCOL_RE.match(settings.MEDIA_URL)


def serialize_date(date: Union[datetime, time]) -> str:
def serialize_date(date: Union[date, datetime, time]) -> str:
"""
Serializes a datetime or time into ISO 8601 format required for Open Graph
and Structured Data.
:param Union[datetime, time] date: The date object to serialize.
:param Union[date, datetime, time] date: The date object to serialize.
:rtype: str
:returns: String-ified date.
"""
Expand Down Expand Up @@ -81,6 +81,10 @@ class StructDataEncoder(JSONEncoder):
def default(self, obj):

# Serialize dates to ISO 8601 format.
if isinstance(obj, date):
return serialize_date(obj)

# Serialize datetimes to ISO 8601 format.
if isinstance(obj, datetime):
return serialize_date(obj)

Expand Down

0 comments on commit dcadbc9

Please sign in to comment.