我正在尝试比较当前日期与之前日期之间的日期和时间,它在IDE上工作但不在我的代码中。谁能告诉我我做错了什么!?
我得到的错误是:
回溯(最近一次呼叫最后一次):文件" read_log.py",第37行,在 如果log_date< current_time和log_date> lastHourTime: TypeError:无法将datetime.datetime与str
进行比较
IDE代码:
Python 2.6.6 (r266:84292, Jul 23 2015, 15:22:56)
[GCC 4.4.7 20120313 (Red Hat 4.4.7-11)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import datetime
>>> current_time = datetime.datetime.now()
>>> print current_time.strftime('%b %d %H:%M:%S')
Feb 19 15:45:49
>>> c= current_time.strftime('%b %d %H:%M:%S')
>>> lastHourTime = datetime.datetime.now() - datetime.timedelta(hours = 1)
>>> l=lastHourTime.strftime('%b %d %H:%M:%S')
>>> print l
Feb 19 14:47:32
>>> print c
Feb 19 15:45:49
>>> print l
Feb 19 14:47:32
>>> l<c
True
>>> l>c
False
>>> m='Feb 7 07:33:19'
>>> m<l
True
>>>
我的脚本代码:
get_date = re.compile('([A-Z-a-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+)(.*)')
current_time = datetime.datetime.now()
lastHourTime = datetime.datetime.now() - datetime.timedelta(hours = 1)
log_file=_read_log()
for line in log_file:
match=re.search(get_date,line)
if match:
log_date= match.group(1).rstrip()
if log_date < current_time and log_date > lastHourTime :
print line
答案 0 :(得分:-1)
您正在将字符串(log_date)与datetime.datetime(current_time)进行比较。
所以我想你想把log_date转换为datetime:
import datetime as dt
d = 'Feb 7 07:33:19'
print(dt.datetime.strptime(d, "%b %d %H:%M:%S").replace(year=dt.date.today().year))
例如:
get_date = re.compile('([A-Z-a-z]+ [0-9]+ [0-9]+:[0-9]+:[0-9]+)(.*)')
current_time = datetime.datetime.now()
lastHourTime = datetime.datetime.now() - datetime.timedelta(hours = 1)
log_file=_read_log()
for line in log_file:
match=re.search(get_date,line)
if match:
log_date = datetime.datetime.strptime(match.group(1).rstrip(), "%b %d %H:%M:%S").replace(year=datetime.date.today().year)
if log_date < current_time and log_date > lastHourTime :
print line