Python 从当前时间获取小时数
我想从现在算起12个小时 当我尝试这个:Python 从当前时间获取小时数,python,python-2.7,Python,Python 2.7,我想从现在算起12个小时 当我尝试这个: # 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]:
# 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"))
我想从当前时间获取小时数,这样我就可以从当前时间向前添加小时数
你能给我举个例子,说明我如何在没有2015051107000
的情况下获得当前时间的小时数吗?首先获得转换时间
处理时间是一件棘手的事情,所以我鼓励你尽可能利用图书馆的电话为你做这项工作。时间数学变得非常混乱,非常快
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
然后读你需要的
随着时间的推移,您可以轻松阅读任何部分的时间,无论是原始时间还是新时间:
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
查看显示值的范围如下所示:
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
要点
时间数学
请注意aretimedelta
,它可以让您轻松地计算时间和日期。操作非常简单,如添加或减去时间的t1=t2+t3
和t1=t2-t3
格式化
使用
strftime
以所需格式输出您的datetime
。您的尝试在哪里,到底有什么问题?@jornsharpe抱歉,请查看更新。我认为OP需要12小时格式的小时。如果是下午1:30,他希望时间是1
而不是13
@letsc你知道我如何用12小时将时间变成1
或当前时间的任何时间吗?请看这里接受的答案-
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
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'