Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Python by (12.7k points)

Let's say I have 24-hours times:

{'Wed': '10:30 - 21:00', 'Sun': '10:30 - 21:00', 'Thu': '10:30 - 21:00', 

 'Mon': '10:30 - 21:00', 'Fri': '10:30 - 22:00', 'Tue': '10:30 - 21:00', 

 'Sat': '10:30 - 22:00'}

Is there any way to convert them to 12-hour time? Like this:

{'Wed': '10:30 AM - 09:00 PM', 'Sun': '10:30 AM - 09:00 PM', 

 'Thu': '10:30 AM - 09:00 PM', 'Mon': '10:30 AM - 09:00 PM', 

 'Fri': '10:30 AM- 10:00 PM', 'Tue': '10:30 AM- 09:00 PM', 

 'Sat': '10:30 AM - 11:00 PM'}

Without if..elif... is there any way to convert them?

1 Answer

0 votes
by (26.4k points)
edited by

Try the following code:

>>> from datetime import datetime

>>> d = datetime.strptime("10:30", "%H:%M")

>>> d.strftime("%I:%M %p")

'10:30 AM'

>>> d = datetime.strptime("22:30", "%H:%M")

>>> d.strftime("%I:%M %p")

'10:30 PM'

Want to learn more topics related to python? Come and join: Python online course

For more details, refer to this video tutorial:

Related questions

0 votes
2 answers
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

28.4k questions

29.7k answers

500 comments

94.1k users

Browse Categories

...