1

I save time in a models name Heures and display it using WebDataRocks library that accept JSON

Doing that, data are display with this format: 08:20:34.234617

How could I display it 08:20:34?

views.py

def index(request):
    data = json.dumps(list(Heures.objects.values('heu_ide','heu_dat','heu_cod','date_id__jou_dat','heu_com','user_id__user__username')), indent=4, sort_keys=True, default=str)


    print(data)
    return render(request, 'export/index.html', {'data':data})```

models.py

class Heures(models.Model):

    _safedelete_policy = SOFT_DELETE_CASCADE
    heu_ide = models.AutoField(primary_key=True)
    date = models.ForeignKey(Jours, on_delete = models.CASCADE, null=True)
    user = models.ForeignKey(Profile, on_delete = models.CASCADE, null=True)
    heu_dat = models.TimeField("Heure du pointage", null=True, blank=True,auto_now_add=True)
    heu_cod = models.IntegerField("Code employé", null=True, blank=True)    
    heu_com = models.CharField("Commentaires", max_length = 150, null=True, blank=True)
    log = HistoricalRecords()

    class Meta:

        db_table = 'crf_heu'
        verbose_name_plural = 'Heures'
        ordering = ['heu_ide']

    def __str__(self):

        return f"{self.heu_dat}"
thorn0
  • 9,362
  • 3
  • 68
  • 96
SLATER
  • 613
  • 9
  • 31

1 Answers1

2

You should use strftime() python function to format your time, e.g.:

def __str__(self):
    return self.heu_dat.strftime("%H:%M:%S")

For the json output, you'd have to loop through the list first, transforming the heu_dat value using strftime(), before doing json.dumps().

Or, if you want to trunk the value directly when fetching it from the database, you can use TruncSecond database function to annotate your query to a value with lower precision:

qs = Heure.objects.annotate(heure=TruncSecond('heu_dat', output_field=TimeField())
data = json.dumps(list(qs.values('heu_ide','heure','heu_cod','date_id__jou_dat','heu_com','user_id__user__username')), indent=4, sort_keys=True, default=str)
dirkgroten
  • 20,112
  • 2
  • 29
  • 42
  • thanks. The second method works: qs = Heures.objects.annotate(heure=TruncSecond('heu_dat')) – SLATER Jan 27 '20 at 15:59
  • @SLATER if an answer solves your problem, you should mark it as accepted by clicking the checkmark on the left of it. This gives both you and the answerer some rep points. – CDJB Feb 07 '20 at 15:14