1

I have this code

import csv

def export_failures_all(request):
    response = HttpResponse(content_type='text/csv')
    response['Content-Disposition'] = 'attachment; filename="failures.csv"'

    writer = csv.writer(response, delimiter=';', dialect = 'excel')
    response.write(u'\ufeff'.encode('utf8'))
    writer.writerow(['Maszyna', 'Wydział', 'Opis', 'Data dodania', 'Data rozpoczęcia naprawy', 'Data zakończenia naprawy', 'Zgłaszający', 'Przyjęte przez', 'Status'])
    awarie = Awaria.objects.all().values_list('maszyna__nazwa', 'wydzial__nazwa', 'description', 'add_date', 'repair_date', 'remove_date', 'user__username', 'sur__username', 'status__nazwa').order_by('-id')

    for awaria in awarie:
        writer.writerow(awaria)

    return response

The problem I have it's with add_date, repair_date, remove_date because there are DateTimeField and in csv file they are with seconds:

2017-02-14 09:50:19.271833+00:00

2017-02-14 08:38:09.362218+00:00

and I want like this:

2017-02-14 09:50

2017-02-14 08:38

Any ideas how to achieve it?

wastl
  • 2,643
  • 14
  • 27
Ein
  • 13
  • 1
  • 4

1 Answers1

1

Format it before by doing:

my_datetime.strftime("%Y-%m-%d %H:%M")

From How do I turn a python datetime into a string, with readable format date?

To update all the dates in your list (assuming its a list of lists)

values_list = [[x.strftime("%Y-%m-%d %H:%M") if isinstance(x, datetime.datetime) else x for x in row] for row in values_list]
Community
  • 1
  • 1
Anfernee
  • 1,445
  • 1
  • 15
  • 26