Hazel, Python, and all that jazz

I’ve been fiddling around with a Python shell script embedded in Hazel that should rename a .pdf file saved to my desktop, then let Hazel file it away in a sub-folder. The new name takes the format ‘EC-’ + year + month. So, for example, June expenses should be filed as EC-201806. Simple enough, but if I file June expenses on the 1st or 2nd of July, I get EC-201807 — not what I’m after, hence the shell script. Trouble is, I’m not in any way proficient in the black art of programming, and my python script is refusing to oblige, though I can’t see any obvious errors (see attached). Any ideas?untitled

If the expenses file contains a date, maybe Hazel could rename the file itself, using Contents-Contains exact match-Date rule.

You could actually use Hazel’s built in functions to rename it, if I understand correctly you’re just using the current date so that should be supported by default :slight_smile:

I‘m really no Python guru but your script seems totally correct. BUT it uses the date function which calls for the actual date of the day the script runs. I see no (easy) way to get a date of an earlier day automatically without requesting it from the user.

So using the Hazel „look inside the file for a date“ function as recommended in the previous comments will be the best bet.

There I was, thinking I was being clever and, meanwhile, the NoodleSoft noodler had made it all so easy! Thanks for pointing me in the right direction folks. Very much appreciated.

1 Like

Try this.

import os
from datetime import date

now = date.today()
day = now.day
month = now.month
year = now.year

if day < 4:
    month -= 1

if month < 1:
    month = 12
    year -= 1

newname = "EC-{0}{1:02}.pdf".format(year, month)

os.rename("Expenses Claim Form.numbers.pdf", newname)

Oohh, clever. Never thought to raise my python skill here. Good point, thank you.

Wow! Thank you. I’d not even considered the year rollover. Off to try it now…

That works a treat! Thank you again. :raised_hands::grinning:

Good, glad I could help.

1 Like