如何将24小时时间转换为12小时时间?

问题描述 投票:40回答:4

我有以下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'}

我怎么能把它转换成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'}

我想智能地转换 "10.30""10.30 AM" &amp。"22:30""10:30 PM". 我可以做使用我自己的逻辑,但有一个方法来做到这一点智能不 if... elif?

python datetime python-3.x python-2.7 string-formatting
4个回答
75
投票
>>> 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'

9
投票

这个代码的关键是使用 库函数 time.strptime() 将24小时的字符串表示解析成一个 time.struct_time 对象,然后使用 库函数 time.strftime() 来格式化这个 struct_time 变成一个你想要的12小时格式的字符串。

我假设你写一个循环没有问题,在dict中的值中迭代,并将字符串分成两个子串,每个子串有一个时间值。

对于每个子串,用这样的代码转换时间值。

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

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


1
投票

Python的strftime使用%I

参考 http:/strftime.org


0
投票
import time

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

以上输出。2020年5月27日7时26分... ...至少现在对我来说是这样;)

© www.soinside.com 2019 - 2024. All rights reserved.