【问题标题】:Django timedelta (DurationField) to secondsDjango timedelta (DurationField) 到秒
【发布时间】:2018-06-15 12:38:47
【问题描述】:

如何在 Django 中将 timedelta 转换为秒?

我有一个 Django 支持的 API,它在某些时候返回一个计算字段:

enhanced_client = client.objects.annotate(duration=ExpressionWrapper((F('end_time')-F('start_time')), output_field=DurationField()))

具有以下值(timedelta):

P0DT00H02M00.102730S

如何在 javascript 中将其转换为秒?我也在使用时刻 js,但我根本无法解析它。

谢谢

【问题讨论】:

    标签: python django django-models momentjs timedelta


    【解决方案1】:

    您可以使用时刻durationasSeconds() getter

    要获取持续时间的秒数,请使用moment.duration().seconds()

    它将返回一个介于 0 和 59 之间的数字。

    如果您想要以秒为单位的持续时间长度,请改用moment.duration().asSeconds()

    var input = 'P0DT00H02M00.102730S';
    console.log( moment.duration(input).asSeconds() );
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>

    【讨论】:

    • 太棒了。有没有办法通过humanize 传递它?或者至少四舍五入?
    • 嗯...这似乎有效。 moment.duration(moment.duration(input).asSeconds(), 'seconds').humanize()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-07
    • 2015-06-22
    • 2021-01-02
    • 2016-03-16
    • 2021-09-07
    • 1970-01-01
    • 2023-01-05
    相关资源
    最近更新 更多