<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:

def query(starttime, endtime, output=None, *filenames):
    '''Given a time range and input file, query creates a new file with only
    that subset of data. If no outfile name is given, the new file name is the
    old file name with the time range appended.

    Args:
        starttime:
            The datetime of the beginning time range to be extracted from the files.
        endtime:
            The datetime of the end of the time range to be extracted from the files.
        output:
            Optional: The output file name. Defaults to
            [first filename in filenames][starttime]-[endtime].pcap
        filenames:
            A tuple of one or more file names to extract data from.
    '''

    if not output:
        output = (filenames[0].replace('.pcap','') + starttime.isoformat() + '-' + endtime.isoformat() + '.pcap')
    else:
        output = output

    with open(output,'w') as outfile:
        for filename in filenames:
            log.info("pcap.query: processing %s..." % filename)
            with open(filename, 'r') as stream:
                for header, packet in stream:
                    if packet is not None:
                        if header.timestamp >= starttime and header.timestamp <= endtime:
                            outfile.write(packet, header=header)