Home > Blockchain >  How to convert users' casual time input to an accepted time format in python DateTimeField?
How to convert users' casual time input to an accepted time format in python DateTimeField?

Time:07-25

In my Django application, there is a field that accepts User/ Admin's input time. The expect outcomes would be:

  1. Input 7 then the system will convert it to 7:00
  2. Input 715, it would be recognized at 7:15. The same 2011 -->20:11, 015-->0015

How should I do it? Any comments?

P.S. I don't have code because I would like to know the apprach first. Thank you!

CodePudding user response:

You might start off with something as simple as this using substring functions.

while True:
    casual = input("Please enter your time:")
    if (casual == "End"):
        break
    if (len(casual) <= 2 or len(casual) > 4):
        print("Please enter three or four digits")
        continue
    if len(casual) == 3:
        hour = casual[0:1]
        if (hour == "0"):
            hour = "00"
        the_time = hour   ":"   casual[1:3]
    else:
        the_time = casual[0:2]   ":"   casual[2:4]
    
    print("The time is:", the_time)

You might want to add in a bit of error checking so that the range of hours is from "00" to "23" and the range of minutes is from "00" to "59".

Hope that helps.

Regards.

CodePudding user response:

This code does what you need

from datetime import time
time_input = input()

if len(time_input) <= 2:
  time_input  = '00'

time_format = time(hour=int(time_input[:-2]), minute=int(time_input[-2:]))

print(time_format)
from datetime import time
time_input = input()

if len(time_input) <= 2:
  time_input  = '00'

time_format = time(hour=int(time_input[:-2]), minute=int(time_input[-2:]))

print(time_format)
  • Related