stratis
stratis

Reputation: 8052

Django timedelta (DurationField) to seconds

How to convert a timedelta to seconds in Django?

I have a Django backed serving an API which at some point returns a calculated field:

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

with the following value (timedelta):

P0DT00H02M00.102730S

How can I turn this into seconds in javascript? I'm also using moment js but I can't parse this at all.

Thanks

Upvotes: 2

Views: 2339

Answers (1)

VincenzoC
VincenzoC

Reputation: 31502

You can use moment duration and asSeconds() getter

To get the number of seconds in a duration, use moment.duration().seconds().

It will return a number between 0 and 59.

f you want the length of the duration in seconds, use moment.duration().asSeconds() instead.

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>

Upvotes: 2

Related Questions