How to sort the files based on the date?

Peter Pearson pkpearson at nowhere.invalid
Mon Jul 15 12:59:12 EDT 2019


On Mon, 15 Jul 2019 09:20:51 +0200, Peter Otten <__peter__ at web.de> wrote:
> Madhavan Bomidi wrote:
>
[snip]
>> 
>> 3RIMG_01APR2018_0514_L2G_AOD.h5
>> 3RIMG_01APR2018_0544_L2G_AOD.h5
>> 3RIMG_01APR2018_0644_L2G_AOD.h5
>> 3RIMG_01APR2018_0714_L2G_AOD.h5
>> 3RIMG_01APR2018_0744_L2G_AOD.h5
[snip]
>> 
>> Can anyone suggest me how I can sort theses files in increasing order of
>> the date on the file name?
>
> Use a key function
>
> filenames = sorted(filename, key=get_datetime)
>
> get_datetime should extract date/time from the filename into a datetime 
> object. The names will then be ordered according to the datetimes' values:
>
> import glob
> import datetime
>
> def get_datetime(filename):
>     parts = filename.split("_")
>     return datetime.datetime.strptime(parts[1] + parts[2], "%d%b%Y%H%M")
>
> filenames = sorted(glob.glob('3RIMG_*.h5'), key=get_datetime)
>
> for fn in filenames:
>     print(fn)


Gorgeous.  This is the best newsgroup ever.

-- 
To email me, substitute nowhere->runbox, invalid->com.



More information about the Python-list mailing list