37

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

  • 9
    1196550000000 is not a unix timestamp, unless we are talking about the year 37,942 or something. –  Aug 12 '09 at 02:10
  • 1
    That looks like a JavaScript timestamp, ms since unix epoch. – 0atman May 26 '11 at 15:21

6 Answers6

108

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.

Nicu Surdu
  • 8,172
  • 9
  • 68
  • 108
John Paulett
  • 15,596
  • 4
  • 45
  • 38
  • Since this solution is so low with no votes I thought I would mention that it worked for me without any issues. Thanks. – michaelavila Mar 14 '11 at 07:16
  • 1
    I'm having issues getting it to work. I can get date and time to output using *any other set of flags*, but when I try to use the "U" flag I get an empty string. I'm boggled. – Blank Mar 25 '11 at 00:09
  • As a side note: it is usually better to store timestamps on DB instead of date strings. Timestamps are absolute (always UTC) and an easy to manipulate integer. – AJJ Jul 11 '11 at 10:15
  • Apparently this is not based on the timezone, but on UTC. To quote the Django docs: `Seconds since the Unix Epoch (January 1 1970 00:00:00 UTC)`. This is also the correct way, since Unix Timestamps are defined to be "seconds since 1970 UTC". – Danilo Bargen Oct 13 '14 at 09:04
70

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')
Mike Fogel
  • 3,127
  • 28
  • 22
28

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 ''
Benjamin Wohlwend
  • 30,958
  • 11
  • 90
  • 100
  • what i don't get: why not use the strftime() method of the date class and be rid of the time module altogether? –  Aug 12 '09 at 02:06
  • hop: `strftime()` returns a string, which isn't always what you want. – Timmmm Sep 27 '12 at 13:42
  • @Pykler, if you want to edit an answer to fix an incorrect statement, then go ahead, but your edit should indeed *remove* the incorrect statement and replace it with a correct one. Otherwise, your edit is no better than a comment to be read after the fact. There's no need to keep the original answer in pristine condition or to specifically highlight updated portions because each post has an edit history where we can see old versions, if anyone's curious enough to look. – Rob Kennedy Sep 20 '13 at 21:00
6

In your views.py, you can convert the value of mydate to seconds since the Unix epoch as follows:

seconds = time.mktime(mydate.timetuple())

Then pass it in the dictionary you use as an argument to render_to_response() (or whatever you're using to render your view), and in your template, stick {{seconds}} into a hidden field, which you can then pull out of the DOM to pass to your javascript graph function.

Note that a DateField maps to the Python object datetime.date, and as such, its timetuple will have its hours, minutes and seconds fields set to 0. If that's not fine-grained enough for you, you'll need to change mydate to a DateTimeField and it'll be a datetime.datetime. You can still use mydate.timetuple() if you do this.

Also, I'm assuming you're using local time. If you're using UTC time, you want calendar.gmtime() rather than time.mktime() and mydate.utctimetuple() rather than mydate.timetuple(), but utctimetuple() is only a valid method for datetime.datetime objects. See the datetime docs (also time and calendar) for more fiddly details.

EDIT: fiddly details such as the fact that mktime() returns a float, which piquadrat remembered and I didn't. The custom-filter approach is also a good one. Voting that one up.

Meredith L. Patterson
  • 4,853
  • 29
  • 30
1

Another option:

import time
from django.utils import timezone

naive_date = timezone.make_naive(mydate, timezone.get_current_timezone())
print int(time.mktime(naive_date.timetuple()))
serg
  • 109,619
  • 77
  • 317
  • 330
0

A very simple way that I did not find in the answers

import time
timestamp = int(time.time())
Oleg Shleif
  • 710
  • 7
  • 24
  • 2
    When adding an answer to a ten year old question with five existing answers it is really important to point out what new aspect of the question your answer addresses. Code only answers can almost always be improved by adding an explanation of how and why they work. – Jason Aller Jun 07 '20 at 00:54