如何及时摆脱零

时间:2014-07-18 14:31:01

标签: python python-2.7

我正在处理我的python脚本以获取当前时间。

当我有01:00PM09:00PM之间的当前时间时,代码将移除0,以便显示1:00PM9:00PM

当我的时间显示在01:00AM09:00AM之间时,它不会删除0

使用此代码:

# Set the date and time row
current_time = time.time() # now (in seconds)
half_hour = current_time + 60*30  # now + 30 minutes
one_hour = current_time + 60*60  # now + 60 minutes

for t in [current_time,half_hour,one_hour]:
    if (0 <= datetime.datetime.now().minute <= 29):
       self.getControl(4204).setLabel(time.strftime("%I").lstrip('0') + ':00' + 
time.strftime("%p"))
       self.getControl(4205).setLabel(time.strftime("%I").lstrip('0') + ':30' + 
time.strftime("%p"))
       self.getControl(4206).setLabel(time.strftime("%I" + ":00%p",time.localtime(t)))
    else:
       self.getControl(4204).setLabel(time.strftime("%I").lstrip('0') + ':30' + 
time.strftime("%p"))
       self.getControl(4205).setLabel(time.strftime("%I" + ":00%p",time.localtime(t)))
       self.getControl(4206).setLabel(time.strftime("%I" + ":30%p",time.localtime(t)))

我不知道如何删除AM的0

您能否告诉我如何删除AM的0

2 个答案:

答案 0 :(得分:0)

为什么你不是lstrip每一段时间?

>>> "01:00AM".lstrip("0")
'1:00AM'
>>> "09:00PM".lstrip("0")
'9:00PM'

此行没有lstrip

self.getControl(4206).setLabel(time.strftime("%I" + ":00%p",time.localtime(t)))

如何添加:

self.getControl(4206).setLabel(time.strftime("%I" + ":00%p",time.localtime(t)).lstrip("0"))

答案 1 :(得分:0)

你不需要做这么复杂的杂技:

>>> import datetime
>>> t = datetime.datetime.now()
>>> t.hour
17

.hour将为您提供24小时的价值。只需检查它是否介于13和21之间,然后相应地格式化您的字符串。

要获得半小时和整整一小时:

>>> t
datetime.datetime(2014, 7, 18, 17, 58, 35, 98698)
>>> t + datetime.timedelta(minutes=30)
datetime.datetime(2014, 7, 18, 18, 28, 35, 98698)
>>> t + datetime.timedelta(hours=1)
datetime.datetime(2014, 7, 18, 18, 58, 35, 98698)
相关问题