0

I have a 24 hour format lets 10:00:00 now I want to randomly generate hours range(1 to 2.5) and add it in a my 24 hour format 10:00:00. e.g

random_hour=0.30 // how I can generate time randomly
24_hour_format=24_hour_format+random_hour  // result should be 10:30:00

I have tried I have used

 timespent=random.uniform(1.0,2.5)
 random_hour="{:.1f}".format(timespent)
 24_hour_format=24_hour_format+random_hour

but it gives me 10:00:00.1.4 // if random number is 1.4 how can I fix this?

Nabeel Ayub
  • 1,060
  • 3
  • 15
  • 35

2 Answers2

1

You need to make use of datetime.timedelta. In this case you should do the following:

import datetime
import random

random_hour = random.uniform(1, 2.5)
given_time = datetime.datetime.utcnow()

new_time = given_time + datetime.timedelta(hours=random_hour)

print(new_time.isoformat())
Daniel Samuels
  • 423
  • 7
  • 25
0

You can use strftime() (from datetime) method to convert to any desired format and print. hope this link will help

Yasir
  • 332
  • 2
  • 9