1

I am trying to pick a random date between a start and an end date. However, I get an error as a result ValueError: Invalid format string

Here is my script. What is the problem here?

start = datetime.datetime.strptime('2022-01-01 00:00:00', '%Y-%m-%d %H:%M:%S')  # Specify start date
end = datetime.datetime.strptime('2022-01-10 00:00:00', '%Y-%m-%d %H:%M:%S')  # Specify end date
def random_datetime(start, end):
    # add check for start, end as datetime
    a = start.strftime('%s')
    b = end.strftime('%s')
    return datetime.datetime.fromtimestamp(random.randint(a, b))
print(random_datetime(start, end))
oobthenewb
  • 15
  • 3
  • 1
    `%s` is not a valid format. See https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes for all the valid formats. What are you expecting `start.strftime('%s')` to return? – Barmar Apr 27 '22 at 22:45
  • 1
    `strftime()` always returns a string. `random.randint()` requires the arguments to be integers. So what do you expect `random.randint(a, b)` to do? – Barmar Apr 27 '22 at 22:47
  • If you want the epoch timestamp, use `start.timestamp()`. See https://stackoverflow.com/questions/19801727/convert-datetime-to-unix-timestamp-and-convert-it-back-in-python – Barmar Apr 27 '22 at 22:49
  • I expect random.randint(a,b) to pick a random date and time between the two specified dates outside of the function. – oobthenewb Apr 27 '22 at 23:24
  • But they're not dates, they're strings. – Barmar Apr 28 '22 at 03:00

1 Answers1

0

I expect random.randint(a,b) to pick a random date and time between the two specified dates outside of the function.

If you are looking for a function that creates a random datetime between the given days:

import datetime
import random

def random_datetime(start, end):
    a = start.timestamp()
    b = end.timestamp()
    return datetime.datetime.fromtimestamp(random.uniform(a, b))
>>> random_datetime(datetime.datetime.strptime('2022-01-01 00:00:00', '%Y-%m-%d %H:%M:%S'), datetime.datetime.strptime('2022-01-10 00:00:00', '%Y-%m-%d %H:%M:%S'))
datetime.datetime(2022, 1, 7, 17, 22, 24, 99912)

random.uniform accepts two numbers as parameters and returns a float in that range, while datetime.timestamp() returns a POSIX timestamp as float.

Xinhe Wang
  • 145
  • 2
  • 9