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.
And if you're not in the template layer, you can still use the same underlying django utils. Ex:
from django.utils.dateformat import formatprint format(mymodel.mydatefield, 'U')
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 timeepoch = int(time.mktime(mydate.timetuple())*1000)
This doesn't work in a Django template though, so you need a custom filter, e.g:
import timefrom django import templateregister = template.Library()@register.filterdef epoch(value): try: return int(time.mktime(value.timetuple())*1000) except AttributeError: return ''