django queryset.values_list() 中日期时间字段到字符串的转换 [英] conversion of datetime Field to string in django queryset.values_list()

查看:31
本文介绍了django queryset.values_list() 中日期时间字段到字符串的转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个查询集,如:

qs = MyModel.objects.filter(name='me').values_list('activation_date')

此处activation_date 是模型中的DateTimeField.当我从这个 qs 下载 Excel 表时,我没有得到 字符串格式的激活日期.如何在字符串中转换此字段('activation_date')或如何在 qs 中对其进行类型转换?

解决方案

https://docs.djangoproject.com/en/2.2/ref/models/fields/#datetimefield

<块引用>

日期和时间,在 Python 中由 datetime.datetime 实例表示.

您可以直接获得 DateTimeField 的字符串表示形式:

str(obj)# obj = qs[0][0] ?或 qs[0][1] ?

你会得到这样的结果(在这个例子中我使用 datetime.datetime.now() 因为 DateTimeFielddatetime.datetime<表示/code> 是相同的行为):

<预><代码>>>>现在 = datetime.datetime.now()>>>str(现在)'2013-06-26 00:14:26.260524'

如果你想要更少的信息或在其他模式下格式化,你可以使用 strftime() 函数来格式化它们.见:

<预><代码>>>>now.strftime('%Y-%m-%d %H:%M')'2013-06-26 00:14'

I have a queryset like:

qs = MyModel.objects.filter(name='me').values_list('activation_date')

here activation_date is DateTimeField in models. When I download excel sheet from this qs I am not getting activation date in string format. How can I convert this field('activation_date') in string or how to typecast it in qs?

解决方案

https://docs.djangoproject.com/en/2.2/ref/models/fields/#datetimefield

A date and time, represented in Python by a datetime.datetime instance.

You can get a string representation of a DateTimeField casting it directly:

str(obj)
# obj = qs[0][0] ? or qs[0][1] ?

You'll get result like this (in this example I use datetime.datetime.now() since a DateTimeField is represented by datetime.datetime is the same behavior):

>>> now = datetime.datetime.now()
>>> str(now)
'2013-06-26 00:14:26.260524'

if you want less information or formatted in other mode you can use strftime() function for format them. see:

>>> now.strftime('%Y-%m-%d %H:%M')
'2013-06-26 00:14'

这篇关于django queryset.values_list() 中日期时间字段到字符串的转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆