在 python 中获得个位数时间

Get single digit time in python

我正在使用以下代码获取 python 中的当前时间。

import datetime
now = datetime.datetime.now()
message_sent_time = now.strftime("%I:%M %p")

returns时间为

06:58 PM

但是,我希望输出为

6:58 PM

即时间在10之前的个位数时间。如何实现?

您可以使用 %-I:

获得一位数小时
>>> message_sent_time = now.strftime("%-I:%M %p")
>>> print(message_sent_time)
7:07 PM

完整 strftime 格式参考:http://strftime.org/