Solution 1 :

I am not sure why it didn’t work for you but I tried and looks like working –

from datetime import datetime, date, time

task_due_hour_raw = "21:02" #I have just hard coded the value I recieved as a request parameter
task_due_hour_split = task_due_hour_raw.split(':')

print(task_due_hour_split[0])
print(task_due_hour_split[1])

task_due_hour = time(int(task_due_hour_split[0]), int(
    task_due_hour_split[1]), 0, 0)

print(task_due_hour)

Problem :

I have a HTML form that takes the input as a hour format. Very simple:

<input type="time" name="due_hour" id="due_hour">

Then I try to convert it to a time format using datetime:

from datetime import datetime, date, time

Here are the first 2 lines of code to convert:

task_due_hour_raw = request.form['due_hour']
task_due_hour_split = task_due_hour_raw.split(':')

If I return f”{task_due_hour_split[0]}:{task_due_hour_split[1]}”, it does print an hour with the correct format, such as 10:00… So the data I try to push into a time type variable seems to be valid.

However, whenever I try to convert it at the last line:

task_due_hour = time(int(task_due_date_split[0]), int(task_due_hour_split[1]), 0, 0)

I get this error message:

ValueError: hour must be in 0..23

If that can be of any use, it’s part of a Flask project. The reason I’m doing this is to convert the data into a time variable so that I can use it in a SQL query to create a new line.

Comments

Comment posted by PacketLoss

Are you looking to include a day and time, or just a time?

Comment posted by G. Langlois

@PacketLoss just a time. The database has two different columns. One for date and one for time.

Comment posted by PacketLoss

If you are to combine the date and time later, could you not just store the time

Comment posted by Nick

In your call to

Comment posted by G. Langlois

@PacketLoss That column in the SQL database is a time format, but I suppose I could just store it as a string and convert it in the code when needed.

By