Search code examples
djangopython-3.xdatetimeviewmilliseconds

How do I output a DateTime field as milliseconds in my view?


I'm using Python 3.7 and Django. I have this field in my model ...

class Article(models.Model):
    ...
    created_on = models.DateTimeField(default=datetime.now)

Then in my view, I'm trying to output this field in a data attribute as milliseconds, so I tried

 data-created-on="{{  article.created_on.timestamp() * 1000 }}"

However, this is resulting in the error when my view is rendered ...

Could not parse the remainder: '() * 1000' from 'article.created_on.timestamp() * 1000'

What's the proper way to output my DateTime field as a time in milliseconds?


Solution

  • You could add a property method to your model to return the time in milliseconds:

    class Article(models.Model):
        created_on = models.DateTimeField(default=datetime.now)
    
        @property
        def created_on_ms(self):
            return self.created_on.timestamp() * 1000
    

    Then in your view you would use the created_on_ms property.

    data-created-on="{{  article.created_on_ms }}"