python 2.7 -将部分字符串转换为整数



我有如下两个unicode和str类型的时间值:

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

我想将time1和time2的整数部分,即10:00和10:15转换为整数,并检查time2> time1。

是否有办法将字符串和unicode的一部分转换为整数?

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;
}

您应该使用datetimetime,它们提供了比较日期时间对象的选项:

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:
    ...

相关内容

  • 没有找到相关文章

最新更新