在 Python 闹钟中减去时间
Subtracting time in a Python Alarm Clock
我目前正在 Python 中为 Raspberry Pi 项目编写闹钟脚本。我需要帮助从当前时间和闹钟时间中解析小时和分钟并将它们转换为秒,以便我可以从闹钟时间中减去当前时间。
下面是如何在 python 中使用日期时间的示例。
from datetime import datetime as dt
import time
format = '%Y-%m-%d %H:%M:%S'
currTime = dt.now()
alarmTime = dt.strptime('2017-12-25 08:00:00', format);
print('current time:\t', currTime)
print('alarm time:\t', alarmTime)
currTimeUnix = time.mktime(currTime.timetuple())
alarmTimeUnix = time.mktime(alarmTime.timetuple())
diff = alarmTimeUnix - currTimeUnix
print('seconds diff: \t', diff)
输出将是:
current time: 2017-12-24 22:40:30.842519
alarm time: 2017-12-25 08:00:00
seconds diff: 33570.0
睡眠示例:
s = 3;
print(dt.now())
time.sleep(s)
print('I\'ve slept for', s, 'seconds')
print(dt.now())
将导致:
2017-12-24 22:44:24.275121
I've slept for 3 seconds
2017-12-24 22:44:27.276324
我目前正在 Python 中为 Raspberry Pi 项目编写闹钟脚本。我需要帮助从当前时间和闹钟时间中解析小时和分钟并将它们转换为秒,以便我可以从闹钟时间中减去当前时间。
下面是如何在 python 中使用日期时间的示例。
from datetime import datetime as dt
import time
format = '%Y-%m-%d %H:%M:%S'
currTime = dt.now()
alarmTime = dt.strptime('2017-12-25 08:00:00', format);
print('current time:\t', currTime)
print('alarm time:\t', alarmTime)
currTimeUnix = time.mktime(currTime.timetuple())
alarmTimeUnix = time.mktime(alarmTime.timetuple())
diff = alarmTimeUnix - currTimeUnix
print('seconds diff: \t', diff)
输出将是:
current time: 2017-12-24 22:40:30.842519
alarm time: 2017-12-25 08:00:00
seconds diff: 33570.0
睡眠示例:
s = 3;
print(dt.now())
time.sleep(s)
print('I\'ve slept for', s, 'seconds')
print(dt.now())
将导致:
2017-12-24 22:44:24.275121
I've slept for 3 seconds
2017-12-24 22:44:27.276324