Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
405 views
in Technique[技术] by (71.8m points)

python 2.7 - conversion of datetime Field to string in django queryset.values_list()

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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'

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...