[Python] Adding Random numbers to the value of datetime.now()

Discussão em 'Python' iniciado por Stack, Julho 30, 2025.

  1. Stack

    Stack Membro Participativo

    Basically, I'm trying to make a program that will calculate the average speed between two points that are 200m apart, and of course convert that into mph so I can say whether it is above or below the speed limit. I'm having problems making it so that it adds random numbers to the value of datetime.now() as it is telling me "NameError: name 'random' is not defined". There's probably an incredibly simple solution to this, I'm just very unsure of how to use the random in this instance. I'm not really sure how to go about fixing this, thanks for any help. Here is my code so far:

    from datetime import date, datetime, time, timedelta
    from random import seed, randrange, uniform
    import time
    def timeDelta():
    print("Average Speed Checker")
    start = (input("Car has passed Cam1: "))
    if start in ("y"):
    camInput1 = datetime.now()
    print(camInput1)
    print("Car is travelling...")
    time.sleep(1)
    print("Car is travelling...")
    time.sleep(1)
    print("Car has passed cam2")
    camInput2 = camInput1 + timedelta(seconds = random.uniform(5, 10))
    timeDelta = camInput2 - camInput1
    distance = 200
    duration = timeDelta.total_seconds()
    print("Time Delta is equal to: {0}".format(duration))
    speedCarMs = distance/duration
    print("Car is travelling in m/s at: {0}".format(speedCarMs))
    speedCarMph = 2.237*speedCarMs
    print("Car is traveelling in MPH at: {0}".format(speedCarMph))


    print("Choose which function you want to use: ")
    while True:
    choice = (input("Choice: "))
    if choice in ("speed"):
    timeDelta()
    else:
    print("Invalid response")

    Continue reading...

Compartilhe esta Página