问题描述
我有一个查询器,如:
qs = MyModel.objects.filter(name='me').values_list('activation_date')
这里 activation_date 是 DateTimeField 在模型中。
当我从这个qs中下载excel表格时,我没有以字符串格式获取激活日期。
如何在字符串中转换此字段('activation_date')或如何转换类型它在qs?
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?
推荐答案
您可以获取DateTimeField转换的字符串表示形式它直接:
You can get a string representation of a DateTimeField casting it directly:
str(obj)
# obj = qs[0][0] ? or qs[0][1] ?
你会得到这样的结果(在这个例子中,我使用datetime.datetime.now(),因为一个DateTimeField由datetime.datetime表示是相同的行为):
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您需要较少的信息或格式化在其他模式下,您可以使用strftime()函数进行格式化。见:
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中将datetime字段转换为字符串queryset.values_list()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!