简体   繁体   中英

Add hours or minutes(randomly generated) in 24 hour format time python

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. eg

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM