Home > Mobile >  how to name a *.tif file with a specific date
how to name a *.tif file with a specific date

Time:08-01

I have to create some *.tif files and I need to name them with specific dates. For example, I have a *.mat file with a 152x380 matrix, each row corresponds to one *.tif file and a specific date (e.g. row 1 correspond to the first *.tif file and I need to name it as 20120101 (YYYYMMDD), the next row is the second *.tif file and its name has to be 20120102 and so on). Do you guys know how to name the *.tif files according the explanation? You can see my code bellow

# Load *.mat file with the precipitation data
root_mat = r"f:\myfile\Precip10km.mat"
mat = scipy.io.loadmat(root_mat)
precipitation = mat['out'] #out variable contains the required data
precipitation = np.array(precipitation)

for i in range(len(precipitation)):
    array = precipitation[i]
    array = np.reshape(array, (19,20))
    driver = gdal.GetDriverByName('GTiff')
    # In this line the variable "output_raster_name" need to assign a specific date
    # (e.g. the first file should be named 20120101, the second 20120102, the third 200120103
    # and so on)
    new_tiff = driver.Create(output_raster_name, array.shape[1],
                                     array.shape[0], 1, gdal.GDT_Int16)


Thanks in advance

CodePudding user response:

you can try it something like:

        from datetime import datetime

        current_time = datetime.now().strftime('%Y-%m-%d_%H:%M:%S')
        file_name = '$your-file-name'   '_'   current_time
        file_format = '$your-file-format'
        
        final_file_name_with_extension = file_name   '.'   file_format

CodePudding user response:

You can use a datetime.date object and add days.

startdate = datetime.date(2022, 7, 29)
for offset, datarow in enumerate(precipitation):
    rowdate = startdate   datetime.timedelta(days=offset)
    filename = rowdate.strftime("%Y%m%d.tif")
    output_raster_name = os.path.join(directory, filename)
    new_tiff = driver.Create(output_raster_name, ...)
  • Related