Home > database >  how to have a TimeField with auto increment of 5 minutes (django)
how to have a TimeField with auto increment of 5 minutes (django)

Time:01-18

I have a model in django that consists of these fields:

device = models.CharField(max_length=150, null=True)

time_received = models.TimeField(auto_now_add=True, null=True)

display_time = [ i want it to have same hour as time_received , minute to be started at 00 and then have interval of 5 and finally second to be 00 ]

the reason i want to do this , is to display time in an orderly manner.

for example:

device A is received at 8:01:20 ---> device A is shown as 8:00:00

device A is received at 8:07:22 ---> device A is shown as 8:05:00

one final note: I need to store both display time and received time in postgresql

thanks for helping

CodePudding user response:

You can accomplish this by creating a custom method on your model that calculates the display_time based on the time_received field.

Create a method on your model that calculates the display_time by taking the hour from the time_received, setting the minutes and seconds to 0, and then adding or subtracting minutes so that the interval is 5.

from datetime import datetime, timedelta

class YourModel(models.Model):
    device = models.CharField(max_length=150, null=True)
    time_received = models.TimeField(auto_now_add=True)
    display_time = models.TimeField(null=True)

    def get_display_time(self):
        hour = self.time_received.hour
        # Convert minute to nearest round of 5
        minute = self.time_received.minute // 5 * 5

        # Create a new datetime object with the calculated hour, minute and second
        display_time = datetime.strptime(f"{hour}:{minute}:00", "%H:%M:%S").time()

        return display_time

    def save(self, *args, **kwargs):
        self.display_time = self.get_display_time()
        super().save(*args, **kwargs)

This way, the display_time will always be rounded to the nearest 5 minute interval, and the seconds will be set to 0.

Personally, I would suggest to create property for this instead of saving in database.

CodePudding user response:

Rather than changing the model field, you can add a property method to floor the value, like this:

import datetime as dt


class YourModel(models.Model):
    ...
    @property
    def display_time(self):
        resolution = dt.timedelta(minutes=5)
        delta = dt.timedelta(seconds=self.recieve_time.seconds%resolution.seconds)
        return self.recieve_time - delta

 
  • Related