Python 如何将 24 小时制转换为 12 小时制?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13855111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 09:45:22  来源:igfitidea点击:

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

pythondatetimepython-3.xpython-2.7string-formatting

提问by Garfield

I have the following 24-hour times:

我有以下 24 小时制:

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

如何将其转换为 12 小时制?

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

我想智能转换"10.30""10.30 AM""22:30""10:30 PM"。我可以使用我自己的逻辑,但是有没有办法在没有if...的情况下智能地做到这一点elif

采纳答案by Tim Pietzcker

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

回答by Jim DeLaHunt

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

此代码的关键是使用库函数time.strptime()将 24 小时制字符串表示形式解析为一个time.struct_time对象,然后使用库函数time.strftime()将其格式化struct_time为您想要的 12 小时制格式的字符串。

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.

我假设您可以轻松编写循环,遍历 dict 中的值并将字符串分成两个子字符串,每个子字符串都有一个时间值。

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.

问题,将字符串转换为日期时间,也有有用的答案。

回答by javis

Python's strftime use %I

Python 的 strftime 使用 %I

reference http://strftime.org/

参考http://strftime.org/

回答by Laurence

import time

# get current time
date_time = time.strftime("%b %d %Y %-I:%M %p")

the above outputs: May 27 2020 7:26 PM ...at least for me right now ;)

以上输出:2020 年 5 月 27 日晚上 7:26 ......至少对我现在来说;)