如何格式化 django 生成的站点地图 lastmod 日期?

How to format django generated sitemap lastmod date?

我的站点地图是这样生成的:

from django.contrib.sitemaps import Sitemap
from django.utils import timezone

class StaticViewSitemap(Sitemap):
    priority = 0.5
    changefreq = 'daily'

        def items(self):
            return ['index', 'contacts']

        def lastmod(self, item):
            return timezone.now()

作为 django 文档 says,lastmod returns 日期时间。它将 sitemap.xml lastmod 呈现为 'yyyy-mm-dd' 格式,看起来是这样的:

<urlset>
    <url>
        <loc>http://127.0.0.1/index</loc>
       <lastmod>2016-10-19</lastmod>
       <changefreq>daily</changefreq>
    </url>
    <url>
       <loc>http://127.0.0.1/contacts</loc>
       <lastmod>2016-10-19</lastmod>
       <changefreq>daily</changefreq>
    </url>
</urlset>

但是我怎样才能将 lastmod 格式更改为 ISO8601(我需要这个:2008-01-02T10:30:00+02:00)才能得到这个:

<urlset>
    <url>
        <loc>http://127.0.0.1/index</loc>
       <lastmod>2016-10-19T00:25:00+03:00</lastmod>
       <changefreq>daily</changefreq>
    </url>
    <url>
       <loc>http://127.0.0.1/contacts</loc>
       <lastmod>2016-10-19T00:25:00+03:00</lastmod>
       <changefreq>daily</changefreq>
    </url>
</urlset>

我试过制作自定义 'formats' 路径,如 here 所述(Django 格式本地化),但没有找到我应该更改哪个设置以获得适当的日期格式。 谢谢。

我的urls.py:

...

sitemaps = {
    'static': StaticViewSitemap
}

urlpatterns = [
    ...
    url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap'),
    ...
]

在内置站点地图模板中,您有 <lastmod>{{ url.lastmod|date:"Y-m-d" }}</lastmod>

您需要覆盖模板并将当前格式固定为 ISO 格式,更多信息就在这里:https://docs.djangoproject.com/en/2.0/ref/contrib/sitemaps/#template-customization

from django.contrib.sitemaps import views

urlpatterns = [
    path('custom-sitemap.xml', views.index, {
        'sitemaps': sitemaps,
        'template_name': 'custom_sitemap.html'
    }),
    path('custom-sitemap-<section>.xml', views.sitemap, {
        'sitemaps': sitemaps,
        'template_name': 'custom_sitemap.html'
    }, name='django.contrib.sitemaps.views.sitemap'),
]

快速link所有格式代码在这里: https://docs.djangoproject.com/en/2.0/ref/templates/builtins/#date