[Solved] what is the elegant way to convert the datetime to str in one element in python list? [closed]


The one-liner way:

import datetime

unit["data"] = [[item.strftime("%Y-%m-%d %H:%m:%S") if isinstance(item, datetime.datetime) else item for item in row] for row in unit["data"]]

As far as I’m concerned I’d wrap this in a couple utility functions though:

import datetime

def format_item(item):
    if isinstance(item, datetime.datetime):
        return item.strftime("%Y-%m-%d %H:%m:%S")
    return item

def format_row(row):
    return [format_item(item) for item in row]

unit["data"] = [format_row(row) for row in unit["data"]]

As a side note:

1/ in your code you’re using a mix of indexed access (unit['data'][idx][0:5] and direct item access (dd[9]) when you could just use dd all over, ie

dd[0:5] + (datetime.datetime.strftime(dd[9], "%Y-%m-%d %H:%m:%S"),) + dd[6:]

2/ even if you needed indexes too, you don’t have to manually maintains the current iteration index (idx in your code), you can just use for index, item in enumerate(sequence):

3/ finally, strftime() is a method of datetime.datetime, so you can just call it directly on your datetime.datetime instance, ie: dd[9].strftime("%Y-%m-%d %H:%m:%S")

1

solved what is the elegant way to convert the datetime to str in one element in python list? [closed]