Home > Software design >  Python concatenate timestamp to list elements
Python concatenate timestamp to list elements

Time:01-14

I want to concatenate timestamp to individual list elements to create a txt or csv file. Here's the code I tried which is concatenating the timestamp to the last element only. So I am doing it wrong. Appreciate any help. Thanks

The expected output is

BSTG,2022-01-13 22:09:07

XTLB,2022-01-13 22:09:07

SERA,2022-01-13 22:09:07

SIDU,2022-01-13 22:09:07

RPID,2022-01-13 22:09:07

BBLN,2022-01-13 22:09:07

SGLY,2022-01-13 22:09:07

DAVE,2022-01-13 22:09:07

GMVD,2022-01-13 22:09:07

BBIG,2022-01-13 22:09:07

# Code Begin
from datetime import datetime

current_results = ['BSTG,XTLB,SERA,SIDU,RPID,BBLN,SGLY,DAVE,GMVD,BBIG']

now = datetime.now()
print(current_results)

for elem in current_results:
    print(str(elem) str(now))

#Code End

CodePudding user response:

There are two problems here that I notice:

1

current_results = ['BSTG,XTLB,SERA,SIDU,RPID,BBLN,SGLY,DAVE,GMVD,BBIG']

is a list with just one str element.

Instead you may want to use:

current_results = ['BSTG', 'XTLB', 'SERA', 'SIDU' , 'RPID', 'BBLN', 'SGLY', 'DAVE', 'GMVD', 'BBIG']

2

When you concatenate results the comma is missing. You may want to use f-strings https://www.python.org/dev/peps/pep-0498/ to format the CSV output easily.

print(f"{elem},{now}")

There are csv specific libraries, e.g. built-in csv but for such a simple case they could be an overkill.

CodePudding user response:

The problem is current_list is a list of 1 element which you need to process before looping:

from datetime import datetime

current_results = ['BSTG,XTLB,SERA,SIDU,RPID,BBLN,SGLY,DAVE,GMVD,BBIG']

now = datetime.now()
print(current_results)
# get the current_results and convert them to a list
current_results = current_results[0].split(',')
# now we can loop and concatenate the time stamp to each result
for res in current_results:
    res = res   ','   now.strftime("%Y-%m-%d %H:%M:%S")
    print(res)

CodePudding user response:

The current_results attribute is a list that contains a single str on it. You can parse your list into a list with every element separated, like this:

from datetime import datetime

current_results = ['BSTG,XTLB,SERA,SIDU,RPID,BBLN,SGLY,DAVE,GMVD,BBIG']
parsed_results = current_results[0].split(",")

now = datetime.now()
print(current_results)

for elem in parsed_results:
    print(str(elem) str(now))

The parsed_results = current_results[0].split(",") will do the trick!

  •  Tags:  
  • Related