blues
blues

Reputation: 373

Convert part of string to integer

I have two time values of type unicode and str like below:

    time1 = "10:00 AM" #type: str
    time2 = "10:15 AM" #type: unicode

I want to convert integer part of time1 and time2 i.e 10:00 and 10:15 to integer and check if time2 > time1.

Is there any way to convert part of string and unicode to integer ?

Upvotes: 0

Views: 196

Answers (2)

vinod reddy
vinod reddy

Reputation: 21

public static void main(String[] args) {

String s1 = "10:00 AM";

String s2 = "10:20 AM";
    int s1_mins = toMinutes(toNumber(s1));
    int s2_mins = toMinutes(toNumber(s2));
    if(s1_mins < s2_mins){
        System.out.println(s2 +" is more than "+ s1);
    }else{
        System.out.println(s1 +" is more than "+s2);
    }
}
private static String toNumber(String s) {
    String[] timeInNumber = s.split(" ");
    return timeInNumber[0];
}
private static int toMinutes(String s) {
    String[] hourMin = s.split(":");
    int hour = Integer.parseInt(hourMin[0]);
    int mins = Integer.parseInt(hourMin[1]);
    int hoursInMins = hour * 60;
    return hoursInMins + mins;
}

The above code helps you.

Upvotes: 1

sshashank124
sshashank124

Reputation: 32189

You should use datetime or time instead which provides an option to compare datetime objects:

from datetime import datetime

time_obj1 = datetime.strptime(time1, '%I:%M %p')
time_obj2 = datetime.strptime(time2, '%I:%M %p')

if time_obj1 > time_obj2:
    ...

Upvotes: 0

Related Questions