django Datefield to Unix timestamp


In a model I have a such field: mydate = models.DateField()

now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.


8/11/2009 9:11:07 AM

Accepted Answer

edit: please check the second answer, it has a much better solution

In python code, you can do this to convert a date or datetime to the Unix Epoch

import time
epoch = int(time.mktime(mydate.timetuple())*1000)

This doesn't work in a Django template though, so you need a custom filter, e.g:

import time

from django import template

register = template.Library()

def epoch(value):
        return int(time.mktime(value.timetuple())*1000)
    except AttributeError:
        return ''
3/20/2015 12:03:48 PM

I know another answer was accepted a while ago, but this question appears high on Google's search results, so I will add another answer.

If you are working at the template level, you can use the U parameter to the date filter, e.g.:

{{ mydate|date:"U" }}

Note that it will be based upon the TIMEZONE in your

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow