Add one hour forward to current time in Python

De openkb
Aller à : Navigation, rechercher

Sommaire

Questions

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?

Answers

You can make computations using seconds from epoch:

import time
t0 = time.time() # now (in seconds)
t1 = t0 + 60*30  # now + 30 minutes
t2 = t0 + 60*60  # now + 60 minutes

for t in [t0,t1,t2]:
   print time.strftime("%I %M %p",time.localtime(t))

output

09 57 PM
10 27 PM
10 57 PM

if you want to round the time to the previous half-hour, add this line:

t0 -= t0 % (30*60) # round down to previous half-hour

Source

License : cc by-sa 3.0

http://stackoverflow.com/questions/24662472/add-one-hour-forward-to-current-time-in-python

Related

Outils personnels
Espaces de noms

Variantes
Actions
Navigation
Outils