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’
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)}')
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)
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()
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’
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)}')
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)
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()