格式化 Django 中以字符串形式提供的日期时间
在我的 Django 应用程序中,我从 Web 服务获取时间(以字符串形式提供),并在模板中使用:
{{date.string}}
这为我提供了一个日期,例如:
2009-06-11 17:02:09+0000
这些显然有点难看,我想以漂亮的方式呈现它们格式给我的用户。 Django 有一个很棒的内置日期格式化程序,它完全可以实现我想要的功能:
{{ value|date:"D d M Y" }}
但是,这期望将值作为日期对象而不是字符串提供。 所以我无法使用它来格式化它。 在 StackOverflow 上搜索之后,pythons strptime 似乎可以满足我的要求,但是对于 Python 来说相当陌生,我想知道是否有人可以想出一种更简单的方法来使用字符串获取日期格式,而不必求助于编写全新的自定义 strptime模板标签?
In my Django application I get times from a webservice, provided as a string, that I use in my templates:
{{date.string}}
This provides me with a date such as:
2009-06-11 17:02:09+0000
These are obviously a bit ugly, and I'd like to present them in a nice format to my users. Django has a great built in date formatter, which would do exactly what I wanted:
{{ value|date:"D d M Y" }}
However this expects the value to be provided as a date object, and not a string. So I can't format it using this. After searching here on StackOverflow pythons strptime seems to do what I want, but being fairly new to Python I was wondering if anyone could come up with an easier way of getting date formatting using strings, without having to resort to writing a whole new custom strptime template tag?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您最好在视图代码中解析从 Web 服务接收到的字符串,然后将 datetime.date (或字符串)传递给模板进行显示。 Django 模板的精髓是,只需在那里完成很少的编码工作; 它们仅用于演示,这就是为什么它们竭尽全力阻止您编写嵌入 HTML 的 Python 代码。
就像:
正如马修指出的那样,这会降低时区。 如果您希望保留与 GMT 的偏移量,请尝试使用优秀的第三方 dateutils 库,它可以无缝处理解析具有时区的多种格式的日期,而无需提供像 strptime 这样的时间格式模板。
You're probably better off parsing the string received from the webservice in your view code, and then passing the datetime.date (or string) to the template for display. The spirit of Django templates is that very little coding work should be done there; they are for presentation only, and that's why they go out of their way to prevent you from writing Python code embedded in HTML.
Something like:
As Matthew points out, this drops the timezone. If you wish to preserve the offset from GMT, try using the excellent third-party dateutils library, which seamlessly handles parsing dates in multiple formats, with timezones, without having to provide a time format template like strptime.
这不涉及 Django 标签,但 strptime 代码是:
请注意,您将删除时区信息。
This doesn't deal with the Django tag, but the strptime code is:
Note that you're dropping the time zone info.