Stefano Potter
Stefano Potter

Reputation: 3577

Converting filename from julian to gregorian date, and reinserting back into filename

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) 

Upvotes: 0

Views: 807

Answers (3)

jfs
jfs

Reputation: 414665

To convert a string into a date object, use datetime.strptime():

>>> from datetime import datetime
>>> datetime.strptime('1985137', '%Y%j')
datetime.datetime(1985, 5, 17, 0, 0)
>>> datetime.strptime('1984137', '%Y%j')
datetime.datetime(1984, 5, 16, 0, 0)

Note: the input is interpreted differently: 1984137 is 1984-05-16 here (137 is interpreted as a day of the year where January 1st is day 1) while datetime(year, 1, 1) + timedelta(day) formula in your question implies that the day is zero-based instead (February 29 is counted in both cases).

To convert date object into a string, use .strftime() method:

>>> datetime(1985, 5, 17, 0, 0).strftime('%Y%m%d')
'19850517'

To replace fixed positions in a filename:

>>> filename = 'LT50300281984137PAC00_sr_band3.tif'
>>> filename[9:16]
'1984137'
>>> new_name = filename[:9] + '19840516' + filename[16:]
>>> new_name
'LT503002819840516PAC00_sr_band3.tif'

To rename a file if the destination might be on a different filesystem, use shutil.move():

>>> import shutil
>>> shutil.move(os.path.join(src_dir, filename), os.path.join(dest_dir, new_name))

If the destination file might exists already; call os.remove(dest_path).

Upvotes: 0

Serge Ballesta
Serge Ballesta

Reputation: 149115

Once you have year and day the method strftime give your result. For 1984 and 137 you get:

import datetime

date=datetime.date(year,1,1)+datetime.timedelta(day)
printf(date.strftime("%4Y%2m%2d"))

19840517

So you can now do:

newFilename = oldFilename[:9] + date.strftime("%4Y%2m%2d") + oldFilename[16:]

Upvotes: 0

Dakkaron
Dakkaron

Reputation: 6276

You could use regex for that:

import re
import os

filename = 'LT50300281984137PAC00_sr_band3.tif'
oldDate = re.sub('(LT5030028)|(PAC00_sr_band3.tif)','',filename) # Extracts the old date
# calculate new date from old date
# newDate = '1984-05-17 00:00:00'
newDate = re.sub('(-)|( .*)','',newDate) # Removes the dashes and the time
newFilename = filename.replace(oldDate,newDate) # Replaces the old date by the new date

os.rename(filename, newFilename) # renames the file to the new file name

Upvotes: 1

Related Questions