我需要将特定格式的字符串转换为另一个。
Source:
2018-08-10 9:00 PM - 9:40 PM
Target:
2018-08-10 21:00:00
我写了以下内容:
def startofappt(strv):
return strv.split(' - ')[0]
def convCalDate(dts, tms):
# 2018-08-08 5:50 PM
from datetime import datetime, date, time
dt = datetime.strptime(str(dts) + ' ' + str(startofappt(tms)), "%Y-%m-%d %H:%M %p")
return str(dt)
import datetime
datetoday = datetime.date.today()
from datetime import datetime, date, time
appointments_set = appointment.objects.filter(docid=11)
for appt in appointments_set:
if appt.date > datetoday:
print("Upcoming: ", appt.date, appt.time, convCalDate(appt.date, appt.time))
else:
print("Other:",appt.date, appt.time, convCalDate(appt.date, appt.time ))
不幸的是我在24小时内遇到问题。
输出:
Upcoming: 2018-08-10 9:00 PM - 9:40 PM 2018-08-10 09:00:00
Other: 2018-08-07 9:40 PM - 10:20 PM 2018-08-07 09:40:00
Other: 2018-08-07 9:00 PM - 9:40 PM 2018-08-07 09:00:00
Upcoming: 2018-08-08 5:50 PM - 6:10 PM 2018-08-08 05:50:00
Upcoming: 2018-08-08 6:10 PM - 6:30 PM 2018-08-08 06:10:00
我在做什么错了?
答案 0 :(得分:1)
能否请您尝试将日期时间读取为12小时格式的日期时间,并在返回日期时将其返回为
def convCalDate(dts, tms):
from datetime import datetime, date, time
dt = datetime.strptime(str(dts) + ' ' + str(startofappt(tms)), "%Y-%m-%d %I:%M %p")
return str(dt)
print convCalDate("2018-08-10", "9:00 PM - 9:40 PM") #returns 2018-08-10 21:00:00
print convCalDate("2018-08-10", "9:00 AM - 9:40 PM") #returns 2018-08-10 09:00:00
希望有帮助