Search code examples
pythondatetimestrptime

How to convert a tuple into a string in python and use it into strptime?


I have a list of tuples in Date[]: [[2017, 1, 1], [2017, 1, 1], . . .

How do I convert each of them into a string?

X=[]
Y=[]
for i in range(len(Date)):
    if(Date[i][0]==2017):
        str=''.join(Date[i])
        X.append(datetime.datetime.strptime(str, '%G %V %u').date())
        Y.append(Val[i])

strptime needs a str to convert, if i add Date[i] there, it says it accepts str not tuple. I tried converting it via str=''join(Date[i]) but it says strptime accepts only str not ints. What seems to be the problem here?


Solution

  • No need to use strptime, you could pass your values to datetime.datetime as they are

    X.append(datetime.datetime(*Date[i]).date())
    

    Also your code needs some polishing, variable names should be lower cased, instead of iterating over range you could iterate directly over values of date and val.

    date = [[2017, 1, 1], [2017, 1, 1]]
    val = [0, 1]
    
    x = []
    y = []
    for i, v in zip(date, val):
        if i[0] == 2017:
            x.append(datetime.datetime(*i).date())
            y.append(v)