mart1n mart1n - 1 year ago 64
Python Question

Convert one item of a tuple in a list of tuples

I have this list of tuples:

b = [(1337345, 'xxx', '2016-05-18 18:44:26.0'),
(1337346, 'yyy', '2016-05-18 18:44:35.0')]

What's the best to convert the date in each of the tuples into the datetime object using
datetime.strptime(my_date, '%Y-%m-%d %H:%M:%S.%f')

I can't directly modify the tuple so I assume this has to be done by building a new list? What's the most efficient way to do this?

Answer Source

I would probably use a list comprehension and build a new tuple with the formatted date:

[(tup[0], tup[1], datetime.strptime(tup[2], '%Y-%m-%d %H:%M:%S.%f') for tup in b]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download