且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何获得小时时间?

更新时间:2023-02-26 17:52:12

正如 Derek 在他的回答中提到的,您可以去除前导零以获得更便携的解决方案.

>>>打印(time.strftime("%I").lstrip('0'))2

如果您在使用 glibc 的 Linux 平台上,您还有一些额外的选择.

选项 1:

使用%l.请注意,这个叶子在开头有一个空格,代替了 0:

>>>打印(时间.strftime(%l"))2

选项 2:

使用%-I.这没有前导 0 或前导空格.

>>>打印(时间.strftime(%-I"))2

这两个选项适用于使用 glibc 的 Linux 系统,因为 Python 使用 strftime() 来自那个库.

I'm working on my python script to get the 12 hours time.

I want to get the 7 hour instead of 07.

self.getControl(4203).setLabel(time.strftime("%I") + ':30' + 
time.strftime("%p"))
print (time.strftime("%I"))

Here is the log:

19:41:47 T:5288  NOTICE: 07

Can you please tell me how I can get the hour time 7 instead of 07?

As Derek mentions in his answer, you can strip leading zeros for a more portable solution.

>>> print(time.strftime("%I").lstrip('0'))
2

If you are on a Linux platform that uses glibc though, you have a few additional options.

Option 1:

Use %l. Notice that this leaves has a space at the beginning, in place of the 0:

>>> print(time.strftime("%l"))
 2

Option 2:

Use %-I. This does not have the leading 0 or leading space.

>>> print(time.strftime("%-I"))
2

These two options work on Linux systems that use glibc, because Python uses the strftime() from that library.