0

I want to create a function that will create a random timestamp and cast into a string. Tried a couple ways but not sure if the problem is using python 2.6

Tried this but running into error that says:

TypeError: unsupported operand type(s) for *: 'datetime.timedelta' and 'float'
def gen_datetime(min_year=2018, max_year=datetime.now().year):

    start = datetime(min_year, 1, 1, 00, 00, 00)

    years = max_year - min_year + 1

    end = start + timedelta(days=365 * years)

    return start + (end - start) * random.random()

...
randomTime = str(gen_datetime())
Clev_James23
  • 171
  • 1
  • 3
  • 15

1 Answers1

0

The multiplication of a datetime.timedelta object with a float was only introduced int Python 3.x. You can confirm this comparing the Datetime docs from Python 2.x and the Datetime docs from Python 3.x

Notice that Python 2.x accepts int and long so it should be fine multiplying it by:

random.randint(a,b)

which will generate an int between a and b

Leonardo Mariga
  • 1,166
  • 9
  • 17
  • That works, however its not giving a random ***time*** along with the date. Any idea why that is happening? And it is not entirely randomizing the date. Im trying this: `return start + (end - start) * random.randint(3,5) ` – Clev_James23 Jul 17 '19 at 22:49
  • The way you did, you are only changing the years of your datetime, not the time. My guess is that you should change your `timedelta(days=365 * years)` and modify the seconds, such as `timedelta(seconds=rondom_seconds)`. [Take a look in nosklo's response here](https://stackoverflow.com/a/553448/11522398). – Leonardo Mariga Jul 17 '19 at 23:01