django Datefield到Unix时间戳 [英] django Datefield to Unix timestamp

查看:228
本文介绍了django Datefield到Unix时间戳的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一个模型中,我有一个这样的字段:
mydate = models.DateField()

In a model I have a such field: mydate = models.DateField()

现在一个javascript图形函数需要unix时间戳,如1196550000000 ,如何返回我的mydate输入的unix时间戳。

now a javascript graph function requires unix timestamp such as "1196550000000", how can I return the unix timestamp of my mydate input.

谢谢

推荐答案

编辑:请检查第二个答案,它有一个更好的解决方案

在python代码中,你可以这样做将日期或日期时间转换为Unix Epoch

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)

这在Django模板中不起作用,所以你需要一个自定义过滤器,例如:

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

这篇关于django Datefield到Unix时间戳的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆