TransWikia.com

How to convert hour into seconds?

Stack Overflow Asked on December 13, 2021

Here For example if the object has hour as 4hr then I want to convert in seconds which should be 14400.

HOURS = (
        ('1', '1 hrs'),
        ('2', '2 hrs'),
        ('4', '4 hrs'),
        ('6', '6 hrs'),
        ('12', '12 hrs'),
        ('24', '24 hrs'),
    )
   
    hour = models.CharField(max_length=5, choices=HOURS)

views.py

obj = MyModel.objects.get(pk=pk)
hour = obj.hour 
# now i Want to convert into seconds.
total_seconds = hour.total_seconds() ??

One Answer

obj.hour is a string, so you can not use .total_seconds() or anything similar. What you can do is use int(…) to convert the number to an int, and then multiply this with 3600 (since one hour is equal to 3'600 seconds):

total_seconds = int(hour) * 3600

It might however make more sense to use an IntegerField [Django-doc] here:

class MyModel(models.Model):
    HOURS = (
        (1, '1 hrs'),
        (2, '2 hrs'),
        (4, '4 hrs'),
        (6, '6 hrs'),
        (12, '12 hrs'),
        (24, '24 hrs'),
    )
   
    hour = models.IntegerField(choices=HOURS)

This will store the value numerically, and thus you do no longer need to call int(…).

Answered by Willem Van Onsem on December 13, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP