0

I have a need to convert a particular formatted string to another.

Source: 2018-08-10 9:00 PM - 9:40 PM Target: 2018-08-10 21:00:00 

I wrote the following:

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 )) 

Unfortunately I'm having trouble with 24 hour time.

Output:

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 

What am I doing wrong?

2
  • Welcome to StackOverflow. Please read and follow the posting guidelines in the help documentation, as suggested when you created this account. Minimal, complete, verifiable example applies here. We cannot effectively help you until you post your MCVE code and accurately describe the problem. We should be able to paste your posted code into a text file and reproduce the problem you described. Commented Aug 7, 2018 at 19:27
  • Make it easy for us: hard-code appointments_set as the list you expect from filter. Commented Aug 7, 2018 at 19:28

1 Answer 1

1

Can you please try reading your date time as 12-hr format date-time and while returning the date return it as

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 

Hope it helps

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.