natnay
natnay

Reputation: 490

Python - Increment time by random variable

I'm trying to increment a time by a random number of minutes. The time is 09:50 and I'd like to increment it by between -5 minutes or +5 minutes. This will be stored as a function. Currently I'm converting my time into seconds since the epoch, then multiplying it by a random variable. However, this changes the value way too much. My code is below:

from scipy.stats import uniform
from datetime import datetime
import time

time_leave = int(time.mktime(time.strptime('2018-08-22 09:50:00','%Y-%m-%d %H:%M:%S')))
time_leave_dist = uniform(.9,1.1)
x = datetime.fromtimestamp(time_leave * time_leave_dist.rvs())
print(x)
2023-08-16 01:08:59.542477

I'm unsure how to convert the random variable from a percentage into time. Any ideas? Thanks!

Upvotes: 0

Views: 262

Answers (1)

J. Blackadar
J. Blackadar

Reputation: 1961

Use random to generate a random number in that range, and add it as minutes:

import random
from datetime import timedelta
increment_delta_minutes = timedelta(minutes=random.randint(-5, 6))
x = x + increment_delta_minutes

Upvotes: 1

Related Questions