“`python Django获取现在和DateTimeField之间的持续时间 “`

huangapple go评论55阅读模式
英文:

Django get duration between now and DateTimeField

问题

我有一个Django模型,其中包含以下字段:

date = models.DateTimeField('开始日期')

我想创建一个持续时间函数,该函数返回当前时间与日期之间的持续时间,格式为"小时:分钟"。

我们如何实现这个功能?

英文:

I have a Django model with the following field:

date = models.DateTimeField('start date')

I want to create a duration function that returns the duration between now and the date in the format "hours:minutes"

How can we achieve this?

答案1

得分: 1

尝试这种方法:

from django.utils import timezone


class Foo(models.Model):
    date = models.DateTimeField()

    def duration(self):
        _seconds = (timezone.now() - self.date).total_seconds()
        _hours = int(_seconds / 3600)
        _minutes = int((_seconds % 3600) / 60)
        return f"{_hours}:{_minutes}"
英文:

Try this approach:

from django.utils import timezone


class Foo(models.Model):
    date = models.DateTimeField()

    def duration(self):
        _seconds = (timezone.now() - self.date).total_seconds()
        _hours = int(_seconds / 3600)
        _minutes = int((_seconds % 3600) / 60)
        return f"{_hours}:{_minutes}"

huangapple
  • 本文由 发表于 2023年2月23日 21:39:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/75545599.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定