0

I'm using python, and I get data from the server, log, so I need to parse the date and time, every day, how can I print just the date and time from this file?

fin = open("data.txt","r")
text = fin.read()
new_date_format1= datetime.datetime.strptime('%Y-%m-%d')
print('Today is:',new_date_format1)

i want for example when running my code print me the date from this file, i don't want to write the date in my code, but i want that my code search inside the file and take the date in format %Y-%m-%d

`2019-02-27 01:13:41,952 INFO  [stdout] (AsyncAppender-Dispatcher-Thread-104)`


2019-02-27 03:45:20,187 INFO [stdout] (AsyncAppender-Dispatcher-Thread-104)

thanks in advance

Dominique
  • 16,450
  • 15
  • 56
  • 112
Network
  • 1
  • 4
  • Can you add the contents in the file? Without it, we'd be unable to tell you how and where the date and time is and how to read it from the file – Devanshu Misra Feb 27 '19 at 09:47
  • Do you want to print the modification timestamp of the file or a date that has been stored as text within the file? If within the file: Does the file only contain the date or do you actually have multiple lines in there (since it is a server logfile) and you want all or a particular date? – ingofreyer Feb 27 '19 at 09:47

1 Answers1

1

Since you are working with a logfile and apparently only want the current date, you could just search for the last line of the (potentially huge) logfile instead of reading the whole file into memory with .read(). This StackOverflow answer has a nice example on how to find the last line of a file.

Once you extracted the latest line in your logfile, you should extrace the date. You can use a regular expression for that. This regex would work for the format you specified:

'^\d+-\d+-\d+\w'

The whitespace \w at the end prevents non-greedy matching from returning wrong (short) results. You can later just use the string method .strip() to remove it.

Once you have the date string, you could use one of the options shown in answers to this StackOverflow question in order to parse a datetime object from it. However, if you want to print it in the same format anyways, then you can also print the extracted String directly.

ingofreyer
  • 1,086
  • 15
  • 27