Python datetime formatted string conversion-24 hour time issue

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP



Python datetime formatted string conversion-24 hour time issue



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?





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.
– Prune
Aug 7 at 19:27





Make it easy for us: hard-code appointments_set as the list you expect from filter.
– Prune
Aug 7 at 19:28


appointments_set


filter




1 Answer
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






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

Firebase Auth - with Email and Password - Check user already registered

Dynamically update html content plain JS

Creating a leaderboard in HTML/JS