Home > Software design >  Extract time from a string
Extract time from a string

Time:01-18

I want user to input and extract hour and mins from the string:

for i in range(0,4):
    # get input
    Str = input("Enter :")
    content = ""
    # print the string
    print("String is : ",Str)
      
    for i in Str:  
        try:
            int(i)
            content = content   i
        except:
            pass
    # get length of string
    length = len(content)
    print("Numbers are : ",content)
    print("Length is : ",length)
    # create a new string of last N characters
    if length >= 4:
        Hour = str(content[-4]) str(content[-3])
        Min = str(content[length - 2:])
    elif length == 3:
        Hour = "0"   str(content[-3])
        Min = str(content[length - 2:])
    elif length == 2:
        Hour = "0"   str(content[-2])
        Min = "0"   str(content[-1])
    else:
        Hour = "0"   str(content)
        Min = "00"
        
    
    Data = Hour   ":"   Min
    # print Last N characters
    print("Time is : ",Data)
Enter :12 hour 5 min
String is :  12 hour 5 min
Numbers are :  125
Length is :  3
Time is :  01:25

Expected :

12:05

CodePudding user response:

You can use the re regular expression module in Python to extract the hour and minutes from a string. Here's an example of how you might do this:

import re

time_string = "The meeting is scheduled for 10:30am"

# Use regular expression to search for a pattern of one or more digits, 
# followed 
# by a colon, followed by one or more digits
match = re.search(r'(\d ):(\d )', time_string)

# Extract the hour and minute from the match
hour = match.group(1)
minute = match.group(2)


print("Hour:", hour)
print("Minute:", minute)

Or you can use "datetime" module. An example:

from datetime import datetime
time_string = "The meeting is scheduled for 10:30am"
time = datetime.strptime(time_string.split("for")[-1].strip(), '%I:%M%p')
print("Hour:", time.hour)
print("Minute:", time.minute)

The output will be

Hour: 10
Minute: 30
  • Related