How to convert string list to date and time list

Question:

I have a string list containing date and time. I want to convert it to date and time list.

lstDateTime = [datetime.strptime(x,'%Y-%m-%d %H:%M:%S.%f') for x in time]
print("lstDateTime:",lstDateTime)

It gives absurd list as
datetime.datetime(2017, 1, 1, 10, 12, 13), datetime.datetime(2017, 1, 1, 10, 12, 14)
while actual string list is like:-
‘2017-01-01 16:59:25.000’, ‘2017-01-01 16:59:26.000’

Asked By: Rahul

||

Answers:

Try this:

lstDateTime = [str(datetime.strptime(x,'%Y-%m-%d %H:%M:%S.%f').isoformat(timespec='milliseconds')) for x in time]
print(f'lstDateTime: {", ".join(lstDateTime)}')
Answered By: Gabio

You are printing the list directly, which causes the objects not to be displayed as formatted strings as you want them to. You can use strftime() to get the desired output. If you want to use the same format as the one you used to convert the strings to datetime objects, you can use this:

lstDateTime = [datetime.strptime(x,'%Y-%m-%d %H:%M:%S.%f') for x in time]
lstDateTime = [x.strftime('%Y-%m-%d %H:%M:%S.%f') for x in lstDateTime]
print("lstDateTime:",lstDateTime)
Answered By: Param Siddharth

Cleanest way is to use pandas, for example with the following test_list as strings:

import pandas as pd
dates = pd.to_datetime(list, format='%Y-%m-%d %H:%M:%S.%f')

This will return a series object. In case you need it as list, convert it:

lstDateTime = date.to_list()
Answered By: jcaliz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.