Home > Mobile >  Get only datetime from list of strings
Get only datetime from list of strings

Time:03-29

lst = ['Last Modified (GMT)', 'Size', '26-Mar-2022 09:17', '',
       '22-Mar-2022 17:30', '', '31-Jan-2022 18:44', '',
       '26-Mar-2022 09:17', '30.8 MB']

How to get only dates from this list of strings in python?

Output should be - 26-Mar-2022 09:17 22-Mar-2022 17:30 31-Jan-2022 18:44 26-Mar-2022 09:17

CodePudding user response:

Since you tagged it pandas, you could use pandas.to_datetime method:

import pandas as pd
out = pd.to_datetime(lst, errors='coerce').dropna().strftime('%d-%b-%Y %H:%M').tolist()

Output:

['26-Mar-2022 09:17', '22-Mar-2022 17:30', '31-Jan-2022 18:44', '26-Mar-2022 09:17']

CodePudding user response:

dates = []
for string in list:
    try:
        date = datetime.strptime(string, '%d-%b-%Y %H:%M')
        dates.append(date)
    except ValueError:
        pass
print(dates)

If you need a purely pythonic solution.

CodePudding user response:

You can use:

from datetime import datetime

out = []
for i in lst:
    try:
        out.append(datetime.strptime(i, '%d-%b-%Y %H:%M'))
    except ValueError:
        pass

Output:

>>> out
[datetime.datetime(2022, 3, 26, 9, 17),
 datetime.datetime(2022, 3, 22, 17, 30),
 datetime.datetime(2022, 1, 31, 18, 44),
 datetime.datetime(2022, 3, 26, 9, 17)]

Maybe you have to define the locale to match the '%b':

import locale
locale.setlocale(locale.LC_TIME, 'C')

CodePudding user response:

You should be able to use itemgetter if I am understanding your request.

from operator import itemgetter

li = ['Last Modified (GMT)', 'Size', '26-Mar-2022 09:17', '', '22-Mar-2022 17:30', '', '31-Jan-2022 18:44', '', '26-Mar-2022 09:17', '30.8 MB']

print(*itemgetter(2, 4, 6, 8)(li))
  • Related