型号域代码是这个
created = models.DateTimeField(auto_now=True)
@property
def now_diff(self):
return timezone.now() - self.created
我对使用虚拟字段进行django时间循环有疑问
时间循环的当前输出为5:26:34.349728
但是我想5:26:34
有办法吗?
感谢让我知道〜!
我追到
@property
def now_diff(self):
s=timezone.now() - self.created
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
return '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))
但是出错
TypeError: 'Todo' object is not subscriptable
TypeError: unsupported operand type(s) for divmod(): 'datetime.timedelta' and 'int'
答案 0 :(得分:2)
从获得的 timedelta
中减去 微秒
from datetime import timedelta
class MyModel(models.Model):
...
created = models.DateTimeField(auto_now=True)
@property
def now_diff(self):
delta = timezone.now() - self.created
return str(delta - timedelta(microseconds=delta.microseconds))
有关更具可读性的解决方案,
from datetime import timedelta
def chop_microseconds(delta):
return delta - timedelta(microseconds=delta.microseconds)
class MyModel(models.Model):
...
created = models.DateTimeField(auto_now=True)
@property
def now_diff(self):
return str(chop_microseconds(timezone.now() - self.created))
如果我们查看 timedelta
类的Source code of __str__()
函数,
....
if self._microseconds:
s = s + ".%06d" % self._microseconds
...
转换timedelta对象的字符串表示形式。
因此,这里我们从timedelta中减去 microsecond ,从而解决了问题:)
答案 1 :(得分:0)
也许您可以这样尝试(主要是从this答案中粘贴副本):
@property
def now_diff(self):
time_delta = timezone.now() - self.created
s = time_delta.seconds
hours, remainder = divmod(s, 3600)
minutes, seconds = divmod(remainder, 60)
return '{:02}:{:02}:{:02}'.format(int(hours), int(minutes), int(seconds))