如何只获得时间值(H:M:S)并在python中进行比较? [英] How to get only time value (H:M:S) and compare it in python?

查看:167
本文介绍了如何只获得时间值(H:M:S)并在python中进行比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在特定时间段内控制设备(模块Raspberry Pi)。我创建一个PHP Web来配置数据库mysql中的时间值。然后我从数据库中抽出时间来比较系统中的时间(实时时钟)。如果系统时间在mysql =>之间的时间之间这是我在mysql中的表(名称:时间):

I want to control devices (module Raspberry Pi) in a certain time period. I make a PHP web to config time value in database mysql. Then I get time from database to compare with time in system (real time clock). If system time is in between time in mysql => led on.
Here is my table(name: time) in mysql:

start_time                      stop_time
07:00:00 (Type: time)           08:00:00 (Type:time)



这是我的代码控制设备:


And here is my code control device:

import MySQLdb
import RPi.GPIO as GPIO
from datetime import date
import time
db_local = MySQLdb.connect("localhost","root","root","luan_van")
with db_local:
      cur = db_local.cursor(MySQLdb.cursors.DictCursor)
      cur.execute("SELECT * FROM time")
      rows = cur.fetchall()
      start = 0
      stop = 0
      for row in rows:
          start = row['start_time']
          stop = row ['stop_time']
tg = strftime("%H:%M:%S", time.localtime())
if( start < tg < stop):
     GPIO.output(12, True)



错误无法将datetime.timedelta与str进行比较。

如何获得系统时间值格式H:M:S?

感谢您的帮助。


It error "can't compare datetime.timedelta to str".
How can I get system time value format "H:M:S"?
Thank for help.

推荐答案

您的问题不是将纯时间与 datetime 隔离开来。你的问题是将时间视为字符串。您无法比较不兼容类型的对象。比较时间与字符串,即使它应该代表时间,在您看来,意味着没有更多的比较时间与短语我是一个害羞的小气球。



即使您可以将 datetime 转换为字符串,也不应该尝试。正确的一般方法是计算 datetime.timedelta 两个时刻。它不仅可以检查相同的时间点,而且还可以检查哪个时刻更早。



请注意,如果你想抽象超出日期并仅比较时间,您可以使用 datetime.time()



这里解释一切: https:// docs .python.org / 2 / library / datetime.html [ ^ ]。



请尝试学习打字的概念和编程的基本概念。尝试使用数据,而不是代表数据的字符串。



-SA
Your problem is not isolating pure time from datetime. Your problem is treating time as string. You cannot compare objects of incompatible types. Comparison time with a string, even it is supposed to represent time, in your opinion, means no more that comparing time with the phrase "I am a little blue balloon in the shy".

You should never try it, even if you can "convert" datetime to string. Correct general approach is calculation of datetime.timedelta for two moments of time. Not only it will give you the check for the identical points in time, but you can also check which moment of time is sooner.

Note that if you want to abstract out the date and compare only the time, you can use datetime.time().

Everything is explained here: https://docs.python.org/2/library/datetime.html[^].

Please try to learn the concepts of typing and basic ideas of programming. Try to work with data, not strings representing data.

—SA


这篇关于如何只获得时间值(H:M:S)并在python中进行比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆