简体   繁体   中英

Python: Working out whitespace in date

I have a log file file.txt and it has the date format as '%b %_d %H:%M:%S' . When the day of the month is between the 1st and 9th, it pads out the field with a space.

I'm just wondering if my code is the best way to check if this includes a space or not as I'm just trying to pull out the date/time from each line

file.txt

Sep  8 16:13:02 blah
Sep  8 16:14:02 blahblah
Sep  8 16:15:02 blablahblah

Code:

with open('file.txt','r') as f:
    for line in f:
        if int(line.split()[1]) < 10:
            d = line.split()[0] + '  ' + line.split()[1] + ' ' + line.split()[2] #double space after [0]
        else:
            d = line.split()[0] + ' ' + line.split()[1] + ' ' + line.split()[2] #single space after [0]
        print d

If you want your output field to be padded with spaces, you can use python string formatting spec .

>>> for line in 'Sep 8 16:13:02 blah', 'Sep 12 16:13:02 blah':
>>>     print('{0} {1:>2} {2}'.format(*line.split()))

Sep  8 16:13:02
Sep 12 16:13:02

{1:>2} means that field 1 should be right aligned and at least 2 characters wide. Missing characters will be padded with spaces.

In python 3.6+ you can also use f-strings to make it more self-explanatory.

>>> for line in 'Sep 8 16:13:02 blah', 'Sep 12 16:13:02 blah blah blah':
>>>     month, date, time, *rest  = line.split() 
>>>     print(f'date: {month} {date:>2} {time}\ncomment: {" ".join(rest)}')

date: Sep  8 16:13:02
comment: blah
date: Sep 12 16:13:02
comment: blah blah blah

Based on the comment by jedwards:

from datetime import datetime

f = '''Sep  8 16:13:02 blah
Sep  8 16:14:02 blahblah
Sep  8 16:15:02 blablahblah'''.splitlines()

for line in f:
    d = datetime.strptime(line[:15], '%b %d %H:%M:%S')
    print(d)

Output:

1900-09-08 16:13:02
1900-09-08 16:14:02
1900-09-08 16:15:02

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM