Home > Back-end >  Invalid format string for datetime
Invalid format string for datetime

Time:04-28

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

CodePudding user response:

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.

  • Related