osdir.com


[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

How to sort the files based on the date?


Madhavan Bomidi wrote:

> I am using the following command line to sort the files:
> 
> import glob
> a = sorted(glob.glob('3RIMG_*.h5')
> 
> Following is the result:
> 
> 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
> 3RIMG_01MAY2018_0515_L2G_AOD.h5
> 3RIMG_01MAY2018_0545_L2G_AOD.h5
> 3RIMG_01MAY2018_0615_L2G_AOD.h5
> 3RIMG_01MAY2018_0645_L2G_AOD.h5
> 3RIMG_01MAY2018_0715_L2G_AOD.h5
> 3RIMG_01MAY2018_0745_L2G_AOD.h5
> 3RIMG_01MAY2018_0815_L2G_AOD.h5
> 3RIMG_02APR2018_0514_L2G_AOD.h5
> 3RIMG_02APR2018_0544_L2G_AOD.h5
> 3RIMG_02APR2018_0614_L2G_AOD.h5
> 3RIMG_02APR2018_0644_L2G_AOD.h5
> 3RIMG_02APR2018_0714_L2G_AOD.h5
> 3RIMG_02APR2018_0744_L2G_AOD.h5
> 3RIMG_02APR2018_0814_L2G_AOD.h5
> 3RIMG_02MAY2018_0515_L2G_AOD.h5
> 3RIMG_02MAY2018_0545_L2G_AOD.h5
> 3RIMG_02MAY2018_0615_L2G_AOD.h5
> 3RIMG_02MAY2018_0645_L2G_AOD.h5
> 3RIMG_02MAY2018_0715_L2G_AOD.h5
> 3RIMG_02MAY2018_0745_L2G_AOD.h5
> 3RIMG_02MAY2018_0815_L2G_AOD.h5
> 3RIMG_31MAR2018_0514_L2G_AOD.h5
> 3RIMG_31MAR2018_0544_L2G_AOD.h5
> 3RIMG_31MAR2018_0614_L2G_AOD.h5
> 3RIMG_31MAR2018_0644_L2G_AOD.h5
> 3RIMG_31MAR2018_0714_L2G_AOD.h5
> 3RIMG_31MAR2018_0744_L2G_AOD.h5
> 
> As you can see from the list of files displayed after sorting, the files
> are not arranged according to the increasing order of the date since the
> date is in the DDMMMYYYY format.
> 
> 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)