How can I convert 24 hour time to 12 hour time?

给你一囗甜甜゛ 提交于 2019-11-26 05:35:11

问题


I have the following 24-hour 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\'}

How can I convert this to 12-hour time?

{\'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\'}

I want to intelligently convert \"10.30\" to \"10.30 AM\" & \"22:30\" to \"10:30 PM\". I can do using my own logic but is there a way to do this intelligently without if... elif?


回答1:


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



回答2:


The key to this code is to use the library function time.strptime() to parse the 24-hour string representations into a time.struct_time object, then use library function time.strftime() to format this struct_time into a string of your desired 12-hour format.

I'll assume you have no trouble writing a loop, to iterate through the values in the dict and to break the string into two substrings with one time value each.

For each substring, convert the time value with code like:

import time
t = time.strptime(timevalue_24hour, "%H:%M")
timevalue_12hour = time.strftime( "%I:%M %p", t )

The question, Converting string into datetime, also has helpful answers.




回答3:


Python's strftime use %I

reference http://strftime.org/



来源:https://stackoverflow.com/questions/13855111/how-can-i-convert-24-hour-time-to-12-hour-time

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!