I have 28 files for example :-
File -> day01.nc
inside file:-
| lat | lon | date |
| --- | --- | -------- |
| 7 | 68 | 2021-02-01|
| 7 | 69 | 2021-02-01|
File -> day02.nc
inside file:-
| lat | lon | date |
| --- | --- | -------- |
| 7 | 68 | 2021-02-02|
| 7 | 69 | 2021-02-02|
File -> day28.nc
inside file:-
| lat | lon | date |
| --- | --- | -------- |
| 7 | 68 | 2021-02-28|
| 7 | 69 | 2021-02-28|
I want to convert their name according to date format like temp_ind20210201.nc
, temp_ind20210202.nc
,...,temp_ind20210328.nc
using python script.
Note :- In day01.nc
the date format inside that file is like 2021-02-01
and so on.
I was trying :-
DATA_DIR = 'data'
today = datetime.datetime.now()
offset_1day = datetime.timedelta(days=1)
re_number = re.compile('day(\d{,2})\.nc')
for fname in glob.glob(DATA_DIR + "/*.nc"):
number_string = re_number.search(fname)
if not number_string:
continue
number_of_days = int(number_string.group(1))
str_timestamp = (today + (number_of_days - 1) * offset_1day).strftime("%Y%m%d")
new_fname = f"{DATA_DIR}/temp_ind{_str_timestamp}.nc"
print(f'{fname} -> {new_fname}')
os.rename(fname, new_fname)
Based on the question and comments beneath it, you want to be able to extract the first date in a NetCDF file and use that to generate a new file name for that file. The following should work, but might need tweaking, depending on how time is formatted: