Reputation: 10419
I want all my files to be off format: 2013-03-31_142436.jpg
i.e. %Y-%m-%d_%H%M%S
I have a script to rename that way but would like to check if the filename is of the format first. I do:
for filename in files:
# check filename not already in file format
filename_without_ext = os.path.splitext(filename)[0];
How do I check filename_without_ext
is of format %Y-%m-%d_%H%M%S
Upvotes: 0
Views: 192
Reputation: 1121942
Just try to parse it as a timestamp:
from time import strptime
try:
strptime(filename_without_ext, '%Y-%m-%d_%H%M%S')
except ValueError:
# Not a valid timestamp
The strptime()
test has the advantage that it guarantees that you have a valid datetime value, not just a pattern of digits that still could represent an invalid datetime ('1234-56-78_987654'
is not a valid timestamp, for example).
Upvotes: 2
Reputation: 142156
Use re
:
import re
if re.match(r'\d{4}-\d{2}-\d{2}_\d{6}$', filename_without_ext):
pass # of the right format
This will just check it looks like it has a chance of being a valid date. Use Martijn's answer if you require it to be a valid date.
Upvotes: 2