3 python time datetime python-2.7
我正在使用我的Python脚本来获取时间.
当我的当前时间是晚上8:30时,我想知道如何在标签中添加小时,这将是晚上9点,晚上9:30?
这是例如:
if (0 <= datetime.datetime.now().minute <= 29):
self.getControl(4203).setLabel(time.strftime("%I").lstrip('0') + ':00' + time.strftime("%p"))
self.getControl(4204).setLabel(time.strftime("%I").lstrip('0') + ':30' + time.strftime("%p"))
self.getControl(4205).setLabel(time.strftime("%I").lstrip('0') + ':00' + time.strftime("%p"))
else:
self.getControl(4203).setLabel(time.strftime("%I").lstrip('0') + ':30' + time.strftime("%p"))
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"))
Run Code Online (Sandbox Code Playgroud)
当我的当前时间是晚上8:30到晚上8:59之间,带有id的标签4203将显示在晚上8:30,带有id的标签4204将显示在晚上8:00,带有id的标签4205将显示在晚上8:30.我希望标签显示为某种东西就像是8:30PM,9:00PM和9:30PM.
你能否告诉我如何使用ID 4204和4205为标签添加一小时?
对于时间偏移,您可以使用datetime.timedelta:
>>> import datetime
>>> datetime.datetime.now()
datetime.datetime(2014, 7, 9, 21, 47, 6, 178534)
>>> datetime.datetime.now() + datetime.timedelta(hours=1)
datetime.datetime(2014, 7, 9, 22, 47, 16, 851338)
Run Code Online (Sandbox Code Playgroud)
至于你的代码,这里有一些改进的例子:
import datetime
# get current time
now = datetime.datetime.now()
# round to half hours
if (now.minute / 30):
# minutes 30-59
minute = 30
else:
# minutes 00-29
minute = 0
now = now.replace(minute=minute, second=0, microsecond=0)
def format(time):
return time.strftime("%I").lstrip('0') + time.strftime(":%M%p")
# set labels
print(4203, format(now))
print(4204, format(now + datetime.timedelta(minutes=30)))
print(4205, format(now + datetime.timedelta(minutes=60)))
Run Code Online (Sandbox Code Playgroud)
这是输出:
(4203, '11:00PM')
(4204, '11:30PM')
(4205, '12:00AM')
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6323 次 |
| 最近记录: |