I'm working on my Python script to get the hours time.
When my current time is 8:30PM, I want to know how I can add the hour forward in the labels which it will be 9:00PM, 9:30PM?
Here is for example:
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"))
When my current time is between 8:30PM and 8:59PM, the label with id 4203 will show 8:30PM, the label with id 4204 will show 8:00PM and the label with id 4205 will show 8:30PM. I want the labels to be display to something is like 8:30PM, 9:00PM and 9:30PM.
Can you please tell me how I can add the one hour forward for the labels following with ids 4204 and 4205?
For time offsets you can use 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)
As for your code, here's an example with couple of improvements:
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)))
And here's the output:
(4203, '11:00PM')
(4204, '11:30PM')
(4205, '12:00AM')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With