Django如何在不使用微秒的情况下使用DateTimeField?

huangapple go评论48阅读模式
英文:

Django how to use DateTimeField without microseconds?

问题

你可以这样获取所需的格式,不包括最后的部分:

representation['created_at'] = instance.created_at.strftime('%Y-%m-%dT%H:%M:%S')

这会将时间字段格式化为 "YYYY-MM-DDTHH:MM:SS" 的形式,省略了毫秒和时区信息。这是使用Python的strftime函数进行的操作。

不过需要注意的是,这将返回一个字符串,而不是日期时间对象。如果需要进行日期时间操作,仍然需要保留原始的created_at字段。

英文:

My field in model:

created_at = models.DateTimeField(auto_now_add=True)

it returns: "created_at": "2023-02-21T09:24:55.814000Z"

how can i get this one (without last part): "created_at": "2023-02-21T09:24:55"

Is there another way instead of this?
(part from the django rest framework serializer)

representation['created_at'] = instance.created_at.split('.')[0]

答案1

得分: 1

你可以使用strftime方法来格式化你想要的日期时间:

created_at.strftime("%Y-%m-%dT%H:%M:%S")
# 应该得到 "2023-02-21T09:24:55"

通常在你的API中,首选ISO-8601格式。你可以使用created_at.isoformat()来获取该格式的字符串表示。

英文:

You can use strftime method to format the datetime in the way you want:

created_at.strftime("%Y-%m-%dT%H:%M:%S")
# Should give "2023-02-21T09:24:55"

Generically in your APIs, ISO-8601 format should be preferred. You can use created_at.isoformat() to get the string representation in that format.

huangapple
  • 本文由 发表于 2023年2月27日 19:13:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/75579729.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定