0

model field code is this

    created = models.DateTimeField(auto_now=True)


    @property
    def now_diff(self):
        return timezone.now() - self.created

I have a question about django time circulation using virtual field

current output of time circulation is 5:26:34.349728

But I want to 5:26:34

Is there a way?

thanks for let me know ~!

i chaged to

    @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))

but error


TypeError: 'Todo' object is not subscriptable

TypeError: unsupported operand type(s) for divmod(): 'datetime.timedelta' and 'int'
Hy K
  • 177
  • 10

2 Answers2

1

Subtract the microseconds from timedelta which you've got

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))

For more readable solution,

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))

Some BG things

If we look into the Source code of __str__() function of timedelta class,

....
if self._microseconds:
    s = s + ".%06d" % self._microseconds
...

which converts the string representation of the timedelta object.
So, here we substract the microsecond from timedelta and hence solved the problem :)

Community
  • 1
  • 1
JPG
  • 82,442
  • 19
  • 127
  • 206
0

Maybe you can try like this(mostly copy pasted from this answer):

@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))
ruddra
  • 50,746
  • 7
  • 78
  • 101