django 日期字段到 Unix 时间戳

发布于 2024-08-02 08:09:46 字数 142 浏览 6 评论 0原文

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

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

谢谢

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

假装爱人 2024-08-09 08:09:47

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

在 python 代码中,您可以执行此操作将日期或日期时间转换为 Unix Epoch

import time
epoch = int(time.mktime(mydate.timetuple())*1000)

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

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

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 ''
丢了幸福的猪 2024-08-09 08:09:47

views.py 中,您可以将 mydate 的值转换为自 Unix 纪元以来的秒数,如下所示:

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

然后将其传递到用作 render_to_response() (或任何您用来渲染视图的内容),然后在模板中,将 {{seconds}} 粘贴到隐藏字段中,然后您可以将其拉出将 DOM 传递给您的 javascript 图形函数。

请注意,DateField 映射到 Python 对象 datetime.date,因此,其 timetuple 将设置小时、分钟和秒字段到 0。如果这对您来说不够细粒度,您需要将 mydate 更改为 DateTimeField,它将是 datetime.datetime。如果您这样做,您仍然可以使用mydate.timetuple()

另外,我假设您使用的是当地时间。如果您使用 UTC 时间,则需要 calendar.gmtime() 而不是 time.mktime()mydate.utctimetuple() 而不是比 mydate.timetuple() 更好,但 utctimetuple() 只是 datetime.datetime 对象的有效方法。请参阅 datetime 文档(还有 time 和 calendar) 了解更多细节。

编辑:一些繁琐的细节,例如 mktime() 返回一个浮点数,piquadrat 记得而我没有。自定义过滤器方法也是一种不错的方法。投票赞成。

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.

伪装你 2024-08-09 08:09:47

另一种选择:

import time
from django.utils import timezone

naive_date = timezone.make_naive(mydate, timezone.get_current_timezone())
print int(time.mktime(naive_date.timetuple()))

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()))
£烟消云散 2024-08-09 08:09:47

我在答案中没有找到一个非常简单的方法

import time
timestamp = int(time.time())

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

import time
timestamp = int(time.time())
楠木可依 2024-08-09 08:09:46

我知道不久前另一个答案已被接受,但这个问题在谷歌搜索结果中排名靠前,所以我将添加另一个答案。

如果您在模板级别工作,则可以使用 U 参数date 过滤器,例如:

{{ mydate|date:"U" }}

请注意,它将基于您的TIMEZONE设置.py。

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.

罪#恶を代价 2024-08-09 08:09:46

如果您不在模板层,您仍然可以使用相同的底层 django utils。前任:

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

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')
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文