Print the Lines of a Log File Which Starts With Date Format "Yyyy-Mm-Dd" in Python

Print the lines of a log file which starts with date format yyyy-mm-dd in Python

Using re.match

Ex:

import re
s = """2018-01-02 This is good
2017-03-22 This is also good
What were you doing on 20-09-2016
2016-09-20 I was working
log file ends"""

for line in s.splitlines():
if re.match(r"\d{4}-\d{2}-\d{2} ", line): #Check if each line matches condition.
print(line)

Output:

2018-01-02 This is good
2017-03-22 This is also good
2016-09-20 I was working

Getting today's date in YYYY-MM-DD in Python?

Use strftime:

>>> from datetime import datetime
>>> datetime.today().strftime('%Y-%m-%d')
'2021-01-26'

To also include a zero-padded Hour:Minute:Second at the end:

>>> datetime.today().strftime('%Y-%m-%d %H:%M:%S')
'2021-01-26 16:50:03'

Date in format of YYYYMMDD rather than YYYY-MM-DD in python

Using strftime:

import datetime
print(datetime.datetime.now().strftime("%Y%m%d"))

OUTPUT:

20190328

Convert date format yyyy-m-d into yyyy-mm-dd on Python

You can use the python inbuilt datetime module

import datetime

date1 = "2018-1-1"
date2 = "2018-01-01"

datetime_object = datetime.datetime.strptime(date1, "%Y-%m-%d")
datetime_object2 = datetime.datetime.strptime(date2, "%Y-%m-%d")

print datetime_object.strftime("%Y-%m-%d")
print datetime_object2.strftime("%Y-%m-%d")

Result:

2018-01-01
2018-01-01

Replacing date in log files with file name with python

you can use regular expression using in python the re module.

In order to replace text using regular expression use the re.sub function:

import re
'''old file data'''
oldfilename = "20480824.txt"
oldtext = " \nblabla foo 2048-08-24 this \n\
2048-08-24 foo bar \n\
2048-08-24: Socket created..."

'''new file data'''
newfilename = "20481023.txt"

'''compute new file data'''
olddate = re.sub(r'(\d{4})(\d{2})(\d{2})\.txt', '\g<1>-\g<2>-\g<3>', oldfilename)
newdate = re.sub(r'(\d{4})(\d{2})(\d{2})\.txt', '\g<1>-\g<2>-\g<3>', newfilename)
newtext = re.sub(r'{}'.format(olddate), '{}'.format(newdate), oldtext)

print("---olddate : " + olddate)
print("---newdate : " + newdate)
print("---oldtext : " + oldtext)
print("---newtext : " + newtext)

output is:

---olddate : 2048-08-24                                                                                                                              
---newdate : 2048-10-23
---oldtext :
blabla foo 2048-08-24 this
2048-08-24 foo bar
2048-08-24: Socket created...
---newtext :
blabla foo 2048-10-23 this
2048-10-23 foo bar
2048-10-23: Socket created...

Python 3 How to format to yyyy-mm-ddThh:mm:ssZ

Try datetime library

import datetime

output_date = datetime.datetime.now().strftime("%Y-%m-%dT%H:%M:%SZ")
print(output_date)

For more information, refer to the Python Documentation.



Related Topics



Leave a reply



Submit