How to compare timestamps in python

MRAB python at mrabarnett.plus.com
Tue Oct 23 15:32:46 EDT 2018


On 2018-10-23 16:18, Asad wrote:
> Hi All ,
> 
>            I have just playing with python , I am stuck for the following
> problem :
> 
> file1 :
> Patching tool version 12.1.0.2.0 Production on Fri Feb 23 01:10:28 2018
> 
> Bootstrapping registry and package to current versions...done
> statement ERR-2001: table is corrupt check for cause
> 
> could not determine the current status.
> 
> Patching tool version 12.1.0.2.0 Production on Fri Feb 23 01:10:58 2018
> 
> file2 :
> 
>   LOG file opened at 02/03/18 01:11:05
> 
> DUP-05004:   statement1
> DUP-05007:   statement2
> 
> 
>   LOG file opened at 02/03/18 01:11:14
> 
> DUP-05004:   statement1
> 
> DUP-05007:   statement2
> 
> 
>   LOG file opened at 02/23/18 01:10:33
> 
> DUP-05004:   statement1
> 
> DUP-05007:   statement2
> 
> I need to look for the ERR-2001 in file1 if it matches then go to file2 and
> print the message nearest to the timestamp found in file1 within two
> minutes of range .
> 
> 
> 1) What regex I use get the timestamp from file 1 and then file 2  ?
> 
> 2) How to I acheive
>   so in this case file1 Start:  Fri Feb 23 01:10:28 2018
>                     End time :  Fri Feb 23 01:10:58 2018
> check in file 2 nearest to file1 end time :     02/23/18 01:10:33
> 
> Thanks in advance,
> 
The datetime in file1 matches this regex:

\b\w{3} \w{3} \d+ \d{2}:\d{2}:\d{2} \d{4}\b

When you have the datetime string, you need to parse it with 
datetime.datetime.strptime; that needs to be given the format that 
describes the datetime:

%a %b %d %H:%M:%S %Y

The datetime in file2 matches this regex:

\b\d{2}/\d{2}/\d{2} \d{2}:\d{2}:\d{2}\b

and the format for datetime.datetime.strptime is:

%m/%d/%y %H:%M:%S

Finding the nearest date/time is simple: calculate the difference 
between the 2 datetimes (which will return a datetime.timedelta) and 
pick the one with the smallest absolute (abs(...)) value of its 
.total_seconds() method.




More information about the Python-list mailing list