I have a Python script that creates PDF Map Books from pre-existing map PDFs, created in ArcGIS Pro. The PDF file names end with the month abbreviation and year they are associated with (example: CACumulativeSumWithin3000_SanBruno_Dec2017.pdf). I want to order the PDFs in the Map Book based on these final 7 charcacters, but the problem is it orders the PDFs alphabetically, so Apr2018 is first instead of Jan2018.

How can I order these PDFs using the month abbreviation and year?

Here is my code:

import arcpy
import os

arcpy.env.workspace = r"E:\arcGIS_Shared\Python\Export\Cumulative_CA2"
path =  r"E:\arcGIS_Shared\Python\Export\Cumulative_CA2"

### Create PDF Map Book File
CApdfPath = os.path.join(path, 'SanBruno_CumulativeHeatMaps.pdf')

CApdfDoc = arcpy.mp.PDFDocumentCreate(CApdfPath)

### List all files in the output folder
CApdfList = arcpy.ListFiles( "CACumulativeSumWithin3000_SanBruno_*")

### Add market title page to the newly created PDF document
CApdfDoc.appendPages(os.path.join(path, "CATitlePage.pdf"))

### Append market specific pages to the PDF
for CApdf in CApdfList:




closed as off-topic by PolyGeo Jun 20 '18 at 18:52

This question appears to be off-topic. The users who voted to close gave this specific reason:

If this question can be reworded to fit the rules in the help center, please edit the question.

  • @BERA I've tried that, but it still sorts alphabetically – Matt A. Jun 20 '18 at 13:31
  • @BERA It still does it alphabetically. Maybe I'm putting it in the wrong location. Do you mind inserting it into the code I've already posted? – Matt A. Jun 20 '18 at 13:43
  • @BERA Yes, I want to sort by the actual date. Sorry if I was unclear in my question. – Matt A. Jun 20 '18 at 13:51
  • 1
    As indicated by @BERA's answer this is a pure Python question that does not require ArcPy to create a code snippet that illustrates where you are stuck. Consequently, it should be researched at Stack Overflow. – PolyGeo Jun 20 '18 at 18:51

Try sorting CApdfList using the datetime module and a lambda function. Insert the sorting after your comment: ### Append market specific pages to the PDF


from datetime import datetime

CApdfList = ['CACumulativeSumWithin3000_SanBruno_Apr2017.pdf','CACumulativeSumWithin3000_SanBruno_Jan2014.pdf']

CApdfList.sort(key=lambda x: datetime.strptime(x[-11:-4],'%b%Y'))

['CACumulativeSumWithin3000_SanBruno_Jan2014.pdf', 'CACumulativeSumWithin3000_SanBruno_Apr2017.pdf']

To understand '%b%Y' see: strptime()

Not the answer you're looking for? Browse other questions tagged or ask your own question.