【问题标题】:Force HTML to show time with seconds from a Python model object强制 HTML 显示来自 Python 模型对象的秒数
【发布时间】:2021-07-18 23:03:24
【问题描述】:

请原谅我对 python 和 web 应用程序的新手身份。
几个小时后,我根本无法让它正常工作。
我想做的就是让表格项目以秒为单位显示时间。
它从views.py中正确打印,但在传递给index.html时似乎进行了一些转换(如console.log上所示)?或者有人可以为我澄清吗?或者请指出我正确的方向?

模型.py:

    class dbMachine100RunTime(models.Model):
        ID = models.AutoField(primary_key=True)
        Machine = models.ForeignKey(Machines, on_delete=models.SET_NULL, null=True, blank=True)
        Date = models.DateField(auto_now=False, default=datetime.now)
        Time = models.TimeField(auto_now=False, default=datetime.now)
        OnOff = models.CharField(max_length=3, default="Error", null=True)
        Count = models.IntegerField(default=0, null=True)
    
        def __str__(self):
            return str(self.Machine)

views.py:

def index(request):
    EndTime = datetime.now()
    TimeDifference = timedelta(hours=1)
    StartTime = EndTime-TimeDifference

    MachineRuntime = dbMachine100RunTime.objects.filter(Time__range=(StartTime, EndTime))
    Machine = MachineRuntime[0].Machine

    print(MachineRuntime[0].Date) #Shows date as = 2021-04-25
    print(MachineRuntime[0].Time) #Shows time as = 10:30:36

    return render(request, 'Machine_Monitor/index.html', {'MachineRuntime': MachineRuntime, 'Machine': Machine})

索引:

{% for item in MachineRuntime %}
          <tr>
            <td>{{item.Date}}</td>
            <td><time step="1">{{item.Time}}</time></td>
            <script>
               console.log("{{item.Date}}"); <!--Shows as: April 25, 2021 -->
               console.log("{{item.Time}}"); <!--Shows as: 10:30 a.m. -->
            </script>
          </tr>
         {% endfor %}

【问题讨论】:

标签: python html django timefield


【解决方案1】:

在你的情况下,这将变成:

{{ item.Time|time:"H:i:s" }}

【讨论】:

    猜你喜欢
    • 2019-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    相关资源
    最近更新 更多