在django queryset.values_list()中将datetime字段转换为字符串

时间:2022-04-20 01:35:36

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?

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

5 个解决方案

#1


15  

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

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

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

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

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

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

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):

你会得到这样的结果(在这个例子中我使用datetime.datetime.now(),因为DateTimeField由datetime.datetime表示是相同的行为):

>>> 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:

如果您想要更少的信息或在其他模式下格式化,您可以使用strftime()函数格式化它们。看到:

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

#2


4  

If you are using Postgres, you can do it like this (date format options here). The solution is database dependent, but it sure beats looping though a long list in Python land after your perform the query.

如果您使用的是Postgres,可以这样做(此处为日期格式选项)。该解决方案依赖于数据库,但在执行查询后,它确实可以通过Python中的长列表进行循环。

qs = MyModel.objects.filter(name='me')
qs = qs.extra(select={'datestr':"to_char(activation_date, 'YYYY-MM-DD HH24:MI:SS')"})
qs = qs.values_list('datestr')

I am sure MySQL has some equivalent function as Postgres's to_char, but you'll have to find that on your own as I am not a MySQL guy.

我确信MySQL有一些与Postgres的to_char相同的功能,但你必须自己找到它,因为我不是MySQL人。

#3


3  

qs = MyModel.objects.filter(name='me')
qs = qs.extra(select={'datestr':"DATE_FORMAT(activation_date, '%Y-%m-%d')"})
qs = qs.values_list('datestr')

#4


2  

extra is deprecated in Django 2.0

在Django 2.0中不赞成使用extra

That's why I think the best solution to get a stringified datetime is:

这就是为什么我认为获得字符串化日期时间的最佳解决方案是:

foo_bar = FooBarModel.objects.annotate(
    str_datetime=Cast(
        TruncSecond('some_datetime_field', DateTimeField()), CharField()
    )
).values('str_datetime').first()

The result is:

结果是:

foo_bar.str_datetime:
(str)'2014-03-28 15:36:55'

Also I'd like to mention that you can format it as well in any way you want like:

另外我想提一下你也可以用你想要的任何方式格式化它:

from django.db.models import Value

foo_bar = FooBarModel.objects.annotate(
    day=Cast(ExtractDay('some_datetime_field'), CharField()),
    hour=Cast(ExtractHour('some_datetime_field'), CharField()),
    str_datetime=Concat(
        Value('Days: '), 'day', Value(' Hours: '), 'hour', 
        output_field=CharField()
    )
).values('str_datetime').first()

The result is:

结果是:

foo_bar.str_datetime:
(str)'Days: 28 Hours: 15'

#5


0  

You can also convert the date in queryset to string using map function. Example:

您还可以使用map函数将queryset中的日期转换为字符串。例:

qs = MyModel.objects.filter(name='me').values_list('activation_date', flat=True)
data = map(str, qs)

#1


15  

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

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

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

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

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

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

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):

你会得到这样的结果(在这个例子中我使用datetime.datetime.now(),因为DateTimeField由datetime.datetime表示是相同的行为):

>>> 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:

如果您想要更少的信息或在其他模式下格式化,您可以使用strftime()函数格式化它们。看到:

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

#2


4  

If you are using Postgres, you can do it like this (date format options here). The solution is database dependent, but it sure beats looping though a long list in Python land after your perform the query.

如果您使用的是Postgres,可以这样做(此处为日期格式选项)。该解决方案依赖于数据库,但在执行查询后,它确实可以通过Python中的长列表进行循环。

qs = MyModel.objects.filter(name='me')
qs = qs.extra(select={'datestr':"to_char(activation_date, 'YYYY-MM-DD HH24:MI:SS')"})
qs = qs.values_list('datestr')

I am sure MySQL has some equivalent function as Postgres's to_char, but you'll have to find that on your own as I am not a MySQL guy.

我确信MySQL有一些与Postgres的to_char相同的功能,但你必须自己找到它,因为我不是MySQL人。

#3


3  

qs = MyModel.objects.filter(name='me')
qs = qs.extra(select={'datestr':"DATE_FORMAT(activation_date, '%Y-%m-%d')"})
qs = qs.values_list('datestr')

#4


2  

extra is deprecated in Django 2.0

在Django 2.0中不赞成使用extra

That's why I think the best solution to get a stringified datetime is:

这就是为什么我认为获得字符串化日期时间的最佳解决方案是:

foo_bar = FooBarModel.objects.annotate(
    str_datetime=Cast(
        TruncSecond('some_datetime_field', DateTimeField()), CharField()
    )
).values('str_datetime').first()

The result is:

结果是:

foo_bar.str_datetime:
(str)'2014-03-28 15:36:55'

Also I'd like to mention that you can format it as well in any way you want like:

另外我想提一下你也可以用你想要的任何方式格式化它:

from django.db.models import Value

foo_bar = FooBarModel.objects.annotate(
    day=Cast(ExtractDay('some_datetime_field'), CharField()),
    hour=Cast(ExtractHour('some_datetime_field'), CharField()),
    str_datetime=Concat(
        Value('Days: '), 'day', Value(' Hours: '), 'hour', 
        output_field=CharField()
    )
).values('str_datetime').first()

The result is:

结果是:

foo_bar.str_datetime:
(str)'Days: 28 Hours: 15'

#5


0  

You can also convert the date in queryset to string using map function. Example:

您还可以使用map函数将queryset中的日期转换为字符串。例:

qs = MyModel.objects.filter(name='me').values_list('activation_date', flat=True)
data = map(str, qs)