0

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) 
Alok Singhal
  • 93,253
  • 21
  • 125
  • 158
Stefano Potter
  • 3,467
  • 10
  • 45
  • 82
  • (1) try to limit your questions to a single issue i.e., `WindowsError` should have been asked as a separate question. Otherwise it makes the question less useful for future visitors. (2) don't put an answer into the question, [post your own answer (and accept it if you'd like) instead](http://stackoverflow.com/help/self-answer) – jfs Aug 14 '15 at 21:50
  • Aside: Time expressed in the form YYYYddd where YYYY is the year and ddd is the day number of the year are not Julian dates. Julian dates are days since noon Universal Time on 01 January 4713 BCE (proleptic Julian calendar). The python datetime module does not handle julian dates. Other python modules such as astropy do. – David Hammen Aug 14 '15 at 22:13
  • @DavidHammen: [*"julian"* means different things in different cases](http://stackoverflow.com/a/25831416/4279). In this case *"julian"* is "zero-based Julian day" from `time` module. – jfs Aug 14 '15 at 22:16

3 Answers3

1

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
Dakkaron
  • 5,930
  • 2
  • 36
  • 51
  • if I want to set `LT5030028` and `PAC00_sr_band3.tif` as variables how would this change the `oldDate = re.sub('(LT5030028)|(PAC00_sr_band3.tif)','',filename)` line? – Stefano Potter Aug 14 '15 at 20:06
  • it would be `oldDate = re.sub('('+varA+')|('+varB+')','',filename)` – Dakkaron Aug 15 '15 at 07:27
0

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:]
Serge Ballesta
  • 143,923
  • 11
  • 122
  • 252
0

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).

jfs
  • 399,953
  • 195
  • 994
  • 1,670