Python: How do you output a datetime variable from a for loop without altering the format?

  datetime, for-loop, python

I have a file with lines containing date and time throughout it, e.g.:

PPS: 0,1096134, Sun Sep 6 16:05:32 2020,,,,,,,,,,,,

I’ve used a for loop to find the lines and extract the date and time values. I’m trying to store the values into a variable ‘date’:

idx = ['PPS']
date = []
from datetime import datetime

with open('output2.csv','r') as input:  
    
    for line in input:
        if  any(idx in line for idx in idx):
            
            dt = line[16:-13]
            dt = datetime.strptime(dt, "%a %b  %d %H:%M:%S %Y")
            print(dt)
            date.append(dt)

print(date)

Printing ‘dt’ in the loop outputs the format I’m looking for:

2020-09-06 16:05:32

But appending ‘dt’ to ‘date’ removes the formatting and outputs the following when printed outside the loop:

datetime.datetime(2020, 9, 6, 16, 5, 32)

Why does this happen and is there a better way of doing this?

Thanks

Source: Python Questions

LEAVE A COMMENT