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

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

Django get duration between now and DateTimeField

问题

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

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

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

我们如何实现这个功能?

英文:

I have a Django model with the following field:

  1. 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

尝试这种方法:

  1. from django.utils import timezone
  2. class Foo(models.Model):
  3. date = models.DateTimeField()
  4. def duration(self):
  5. _seconds = (timezone.now() - self.date).total_seconds()
  6. _hours = int(_seconds / 3600)
  7. _minutes = int((_seconds % 3600) / 60)
  8. return f"{_hours}:{_minutes}"
英文:

Try this approach:

  1. from django.utils import timezone
  2. class Foo(models.Model):
  3. date = models.DateTimeField()
  4. def duration(self):
  5. _seconds = (timezone.now() - self.date).total_seconds()
  6. _hours = int(_seconds / 3600)
  7. _minutes = int((_seconds % 3600) / 60)
  8. 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:

确定