django Datefield to Unix timestamp

django, python, unix-timestamp

Solution

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

@register.filter
def epoch(value):
    try:
        return int(time.mktime(value.timetuple())*1000)
    except AttributeError:
        return ''

Problem

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. Thanks

Original source