简体   繁体   English

类型错误:无法将 datetime.datetime 与 datetime.time 进行比较

[英]TypeError: can't compare datetime.datetime to datetime.time

I'm trying to parse a string which has a military time hour value我正在尝试解析一个具有军事时间小时值的字符串

'10:00:00'

I am able to do this with我能够做到这一点

>>> datetime.datetime.strptime('10:00:00', '%H:%M:%S').time()
datetime.time(10, 0)

Then I get the current time in a specific time zone:然后我获取特定时区的当前时间:

>>> datetime.datetime.utcnow()+ datetime.timedelta(hours=10)
datetime.datetime(2017, 8, 3, 11, 26, 1, 909000)

What I'm trying to do is compare the time from the string with the current time in utc.我想要做的是将字符串中的时间与 utc 中的当前时间进行比较。 But when I compare the values但是当我比较这些值时

>>> bne_time_now > tag_time
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: can't compare datetime.datetime to datetime.time

What I think I need to do is set a default time value when I parse the string but I am not sure how to do this?我认为我需要做的是在解析字符串时设置默认时间值,但我不确定如何执行此操作?

Convert your datetime.datetime object to a datetime.time object using the time() method.使用time()方法将datetime.datetime对象转换为datetime.time对象。

>>> (datetime.datetime.utcnow() + datetime.timedelta(hours=10)).time()
datetime.time(11, 33, 51, 523382)

Then you can compare the two time objects.然后您可以比较两个时间对象。

So I managed to get this working:所以我设法让这个工作:

>>> today = datetime.datetime.utcnow()
>>> today
datetime.datetime(2017, 8, 3, 1, 52, 33, 253000)
>>> datetime.datetime.strptime('10:00:00', '%H:%M:%S').replace(year=today.year, month=today.month, day=today.day)
datetime.datetime(2017, 8, 3, 10, 0)

just posting here in case someone else needs this solution只是在这里发布以防其他人需要这个解决方案

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM