我正在尝试将某些数据从csv转换为特定的json数据结构,并具有以下单独示例格式的字符串: “ 8:30 AM-12:30 PM” “ 12:00 PM-2:00 PM” 其中“-”之前的时间是开始时间,而“-”之后的时间是结束时间。我一直试图将它们分成24hr格式的startTime和endTime两个变量。 例子:
startTime = 0830 endTime = 1230
startTime = 1200 endTime = 1400
答案 0 :(得分:1)
def get_24_format(time):
timeinstr = ""
if len(time.split(":")[0]) is 1:
if time[len(time)-2] == 'A':
timeinstr += "0{}".format(time.split(":")[0])
else:
timeinstr += "{}".format(int(time.split(":")[0])+12)
else:
if time[len(time)-2] == 'A':
timeinstr += "{}".format(time.split(":")[0])
else:
timeinstr += "{}".format(int(time.split(":")[0])+12)
timeinstr += time.split(":")[1][:2]
return timeinstr
# input your time here
# time = "11:00PM - 2:00AM"
time = time.split("-")
time[0] = time[0].rstrip()
time[1] = time[1].lstrip()
timeinstr = "starttime " + get_24_format(time[0]) + " endtime " + get_24_format(time[1])
print(timeinstr)
答案 1 :(得分:0)
尝试:
from datetime import *
time1 = "12:00PM - 2:00PM"
# Splitting the string into two parts (using the hyphen in between them) and storing them in two separate variables
# t1 = start time; t2 = end time
t1, t2 = time1.split(" - ")
# string manipulation to make the data feedable to datetime.strptime()
t1 = t1.replace("AM", " AM").replace("PM", " PM")
t2 = t2.replace("AM", " AM").replace("PM", " PM")
# passing the data stored in our strings and converting it into 24hr format
t1 = datetime.strptime(t1, '%I:%M %p')
t1 = datetime.strftime(t1, "%H:%M")
t2 = datetime.strptime(t2, '%I:%M %p')
t2 = datetime.strftime(t2, "%H:%M")
print(t1)
print(t2)
输出:
12:00
14:00