django Datefield to Unix timestamp

前端 未结 6 1372
天涯浪人
天涯浪人 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:40

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

提交回复
热议问题