django Datefield to Unix timestamp

前端 未结 6 1371
天涯浪人
天涯浪人 2020-12-05 02:08

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 u

6条回答
  •  南方客
    南方客 (楼主)
    2020-12-05 02:49

    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.

提交回复
热议问题