I have a bunch of files names like so:
LT50300281984137PAC00_sr_band3.tif
LT50300281985137PAC00_sr_band1.tif
And I want to change the julian date contained in [9:16] of each filename to gregorian date, and then reinsert the new date back into the filename. I have converted for julian to gregorian using this code:
import datetime, glob, os
for raster in glob.glob('r'F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\julian_dates/*.tif'):
year=int(oldFilename[9:13])
#the day
day=int(oldFilename[13:16])
#convert to julian date
date=datetime.datetime(year,1,1)+datetime.timedelta(day)
print date
This will give me the julian date for each file, so for a file like this LT50300281984137PAC00_sr_band3.tif
, this would be returned 1984-05-17 00:00:00
, but I don't want the 00:00:00
and I want to insert the gregorian date back into the filename, preferable as 19840517
.
Edit:
Using suggestions from all of the answers so far I am able to do everything but execute the rename (last line of code in this example) using this:
import datetime, glob, os
for raster in glob.glob(r'F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\julian_dates/*.tif'):
oldFilename=raster
year=int(oldFilename[9:13])
#the day
day=int(oldFilename[13:16])
#convert to julian date
date=datetime.datetime(year,1,1)+datetime.timedelta(day)
#generate newfile names
newFilename=oldFilename[:9] + date.strftime('%Y%m%d') + oldFilename[16:]
#rename the files
os.rename(oldFilename, newFilename)
this returns error: WindowsError: [Error 2] The system cannot find the file specified
and I think it may have something to do with my os pathway. All other variables till this point populate as expected.
Edit: This code works for me
arcpy.env.workspace=r'F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\julian_dates'
hank_bands='F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\julian_dates'
hank_out='F:\Sheyenne\Atmospherically Corrected Landsat\hank_masked\greg_dates'
list1=arcpy.ListRasters("*.tif")
for raster in list1:
source_path = os.path.join(hank_bands, raster)
oldFilename=raster
year=int(oldFilename[9:13])
#the day
day=int(oldFilename[13:16])
#convert to julian date
date=datetime.datetime(year,1,1)+datetime.timedelta(day)
newFilename=oldFilename[:9] + date.strftime('%Y%m%d') + oldFilename[16:]
destination_path=os.path.join(hank_out, newFilename)
os.rename(source_path, destination_path)