django Datefield to Unix timestamp

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 settings.py.


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 ''

And if you're not in the template layer, you can still use the same underlying django utils. Ex:

from django.utils.dateformat import format
print format(mymodel.mydatefield, 'U')