[Django]-Django expression DateTime and Integer seconds

5👍

I found a solution: Convert the integer to a duration using the ExpressionWrapper. As I am getting seconds and a DurationField() is Microseconds, I have to multiply them by 1,000,000.

last_reboot=ExpressionWrapper(
    F('last_report') - ExpressionWrapper(
        F('uptime') * 1000000,
        output_field=DurationField()
    ),
    output_field=DateTimeField()
)

1👍

Previously, I did something like below…might be useful for others.

.annotate(timestamp=RawSQL('DATE(milisecond_datetimestamp, \'unixepoch\')',[])) 

and another query where I had to convert the date integer field to hour

.annotate(hour=Round(F('milisecond_datetimestamp') % (3600 * 24) /3600)) 

and for Round you have to define SQL function like below

class Round(Func):
    function= 'ROUND'

Leave a comment