有没有办法比较两个日期而不是每次在python中调用strptime?我确定我的问题没有其他方法,但我想确保我已经检查了所有选项.
我正在浏览一个非常大的日志文件,每行都有一个我需要比较的日期,以查看该日期是否在其他两个日期的范围内.我不得不用strptime转换每一行的每个日期,这会导致一个巨大的瓶颈;
Fri Sep 2 15:12:43 2016 output2.file
63518075 function calls (63517618 primitive calls) in 171.409 seconds
Ordered by: cumulative time
List reduced from 571 to 10 due to restriction <10>
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.003 0.003 171.410 171.410 script.py:3(<module>)
1 0.429 0.429 171.367 171.367 scipt.py:1074(main)
1 3.357 3.357 162.009 162.009 script.py:695(get_data)
1569898 14.088 0.000 141.175 0.000 script.py:648(check_line)
1569902 6.899 0.000 71.706 0.000 {built-in method strptime}
1569902 31.198 0.000 64.805 0.000 /usr/lib64/python2.7/_strptime.py:295(_strptime)
1569876 15.324 0.000 43.170 0.000 …Run Code Online (Sandbox Code Playgroud) 当我得到一个小时的时间时,它会像这样在24小时制中打印出来;
time1 = datetime.datetime.strptime("08/Jan/2012:08:00:00", "%d/%b/%Y:%H:%M:%S")
print 'hour is ', time1.hour
> time is 8
Run Code Online (Sandbox Code Playgroud)
我试图将其显示为08,而不是8。对于小时而言,两位数是可以的,但是一旦达到一位数,我就会尝试使其前面的0。
我可能会做“ time1.time”,然后转换为字符串,然后将其拆分,然后将小时转换回日期时间对象,但这耗时很长,并且想知道是否有一个更简单的解决方案?
我有以下两个字符串;
line1 = [16/Aug/2016:06:13:25 -0400] "GET /file/ HTTP/1.1" 302 random stuff ignore
line2 = [16/Aug/2016:06:13:25 -0400] "" 400 random stuff ignore
Run Code Online (Sandbox Code Playgroud)
我想抓住这两个部分;
"GET /file/ HTTP/1.1" 302
"" 400
Run Code Online (Sandbox Code Playgroud)
基本上两个"之间的任何字符"或"之间没有任何东西".到目前为止,我已经尝试过了;
regex_example = re.search("\".+?\" [0-9]{3}", line1)
print regex_example.group()
Run Code Online (Sandbox Code Playgroud)
这将与line1一起使用,但为line2提供错误.这是由于'.' 匹配任何字符,但如果不存在字符则给出错误.
有没有办法让它匹配两个""之间的任何字符或什么都没有?
我试图弄清楚打开python文件的最佳方法是基于它的类型.
例如,我有一些像这样的基本东西,但它对我来说似乎并不"pythonic",我觉得它在某种程度上可以重构和编写得更清洁;
def openfile(filename):
if read_file_from_top:
if not filename.endswith('.gz'):
with open(filename, 'r') as infile:
for line in infile:
# do something
else:
with gzip.open(filename, 'r') as infile:
for line in infile:
# do something
elif read_file_from_bottom:
if not filename.endswith('.gz'):
with open(filename, 'r') as infile:
for line in infile:
# do something
else:
with gzip.open(filename, 'r') as infile:
for line in infile:
# do something
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来做到这一点,也许使用发电机?谢谢.
寻找有关如何使用 *args 正确解压缩其他函数中的返回参数的指导?这是代码;
#!/usr/bin/python
def func1():
test1 = 'hello'
test2 = 'hey'
return test1, test2
def func2(*args):
print args[0]
print args[1]
func2(func1)
Run Code Online (Sandbox Code Playgroud)
我收到的错误信息;
<function func1 at 0x7fde3229a938>
Traceback (most recent call last):
File "args_test.py", line 19, in <module>
func2(func1)
File "args_test.py", line 17, in func2
print args[1]
IndexError: tuple index out of range
Run Code Online (Sandbox Code Playgroud)
我已经尝试了一些事情,args()但没有成功。尝试打开包装时我做错了什么?