D_P
D_P

Reputation: 862

How to convert hour into seconds?

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() ??

Upvotes: 2

Views: 197

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

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(…).

Upvotes: 1

Related Questions