Rob
Rob

Reputation: 181

getting the hour from current time

I want to get the 12 hours from the current time.

when i try this:

# 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(346).setLabel(time.strftime("%I" + ":30%p",time.localtime(t)).lstrip("%p"))
    else:
        self.getControl(346).setLabel(time.strftime("%I" + ":30%p",time.localtime(t)).lstrip("0"))

it will not get the hour from the current time to add the hours, as because i'm using time.strftime("%I"

I want to get the hours from the current time to get the hours and add the hours.

The return output would be:

7

I want to get the hours from the current time so i could then add the hours forward from the current time.

Can you show me of example how I can get the hours from current time without the 20150511070000?

Upvotes: 1

Views: 351

Answers (1)

Ezra
Ezra

Reputation: 7702

First Get the Shifted Time

Dealing with times is tricky, so I encourage you to use library calls to do the work for you wherever possible. Time-math gets really messy, really fast.

from datetime import datetime, timedelta

original_time = datetime.now() # datetime.datetime(2015, 5, 11, 12, 32, 46, 246004)
print(original_time) # 2015-05-11 12:32:46.246004

offset = timedelta(hours=12) # datetime.timedelta(0, 43200)
shifted_time = original_time + offset # datetime.datetime(2015, 5, 12, 0, 32, 46, 246004)
print(shifted_time) # 2015-05-12 00:32:46.246004

Then Read What You Need

With the time shifted, you can easily read any part of the time, on either the original time, or the new time:

original_time # datetime.datetime(2015, 5, 11, 12, 32, 46, 246004)
original_time.hour # 12
original_time.year # 2015
original_time.month # 5
original_time.day # 11
original_time.hour # 12
original_time.minute # 32
original_time.second # 46

Looking at the Datetime Documentation shows you that the ranges for the values are as follows:

MINYEAR <= year <= MAXYEAR
1 <= month <= 12
1 <= day <= number of days in the given month and year
0 <= hour < 24
0 <= minute < 60
0 <= second < 60

Then Format and Print

If you need another behaviour for printing, use strftime, as you have been.

datetime.strftime(original_time, "%I") # '12'
datetime.strftime(original_time, "%I:30%p") # '12:30PM'
datetime.strftime(shifted_time, "%I:30%p") # '12:30AM'
datetime.strftime(shifted_time, "%Y %H %M %S") # '2015 00 32 46'
datetime.strftime(original_time, "%Y %H %M %S") # '2015 12 32 46'

Key Points

Time Math

Be aware of are timedelta which allows you to easily perform math on times and dates. Operations are as simple as t1 = t2 + t3 and t1 = t2 - t3 to add or subtract times.

Formatting

Use strftime to output your datetime in the desired format.

Upvotes: 1

Related Questions