Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Django:在JSON中显示时如何格式化时间(hh:mm:ss)?_Python_Django_Webdatarocks - Fatal编程技术网

Python Django:在JSON中显示时如何格式化时间(hh:mm:ss)?

Python Django:在JSON中显示时如何格式化时间(hh:mm:ss)?,python,django,webdatarocks,Python,Django,Webdatarocks,我用一个名为Heures的模型来节省时间,并使用接受JSON的WebDataRocks库来显示它 这样,数据将以以下格式显示:08:20:34.234617 我如何显示它08:20:34 视图.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__userna

我用一个名为Heures的模型来节省时间,并使用接受JSON的WebDataRocks库来显示它

这样,数据将以以下格式显示:08:20:34.234617

我如何显示它08:20:34

视图.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})```
型号.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})```
类Heures(models.Model):
_安全删除策略=软删除级联
heu\u ide=models.AutoField(主键=True)
日期=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-employee”,null=True,blank=True)
heu_com=models.CharField(“评论”,最大长度=150,null=True,blank=True)
日志=历史记录()
类元:
db_表='crf_heu'
详细名称复数='Heures'
排序=['heu_ide']
定义(自我):
返回f“{self.heu_dat}”
您应该使用python函数设置时间格式,例如:

def __str__(self):
    return self.heu_dat.strftime("%H:%M:%S")
对于json输出,在执行
json.dumps()
之前,必须首先循环遍历列表,使用
strftime()
转换
heu dat

或者,如果要在从数据库获取值时直接对其进行中继,可以使用数据库函数将查询注释为精度较低的值:

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)

谢谢第二种方法有效:qs=Heures.objects.annotate(heure=truncsond('heu_dat'))@SLATER如果答案解决了您的问题,您应该通过单击其左侧的复选标记将其标记为已接受。这给了你和回答者一些代表点。