Convert julian day into date

19,748

Solution 1

Use the datetime module to get date from day of the year. I am assuming the year is 2007 as in your examples, since your filenames do not seem to have an year value. Feel free to replace the hardcoded 2007 in the code with a variable if required.

import datetime
oldFilename = 'day00364.nc'
day = int(oldFilename[3:-3])
date = datetime.datetime(2007, 1, 1) + datetime.timedelta(day) #This assumes that the year is 2007
newFilename = 'day%s.nc'%date.strftime('%Y%m%d')
print newFilename # prints day20071231.nc

For those who are downvoting this answer because "this solution adds a day"

The OP's files are numbered 0 to 364, not 1 to 365. This solution works for the OP. In case your dates are from 1 to 365, and it's not at all obvious to you, please freel free to subtract "1" from the day variable before converting it to a timedelta value.

Solution 2

datetime has a build in julian converter in it's strptime function using the %j format specifier. Assuming that your files are 'day' two digit year + julian + extention (if not, just add whatever year offset you really have)

file_date = filename[3:-3]
file_date = datetime.datetime.strptime(file_date, '%y%j').strftime('%Y%m%d')
new_filename = file_date.strftime('day%Y%m%d.nc')

after comment about how to get the year

year = datetime.datetime.fromtimestamp(os.path.getctime(filename)).year
file_date = datetime.datetime.strptime(filename[5:-3], '%j').replace(year=year)
new_filename = file_date.strftime('day%Y%m%d.nc')

Solution 3

With GNU awk and any Bourne-like shell

for old in *
do
    new=$( gawk -v old="$old" 'BEGIN{
            secs = (gensub(/[^[:digit:]]/,"","g",old) + 1) * 24 * 60 * 60
            print gensub(/[[:digit:]]+/,strftime("%Y%m%d",secs),"",old)
        }' )
    echo mv "$old" "$new"
done

Remove the "echo" after testing.

Share:
19,748
user2050187
Author by

user2050187

Updated on June 04, 2022

Comments

  • user2050187
    user2050187 almost 2 years

    I have files named day00000.nc, day00001.nc, day00002.nc, ...day00364.nc for several years. They represent the 365 or 366 days. I want to rename my files like this day20070101.nc, day20070102.nc , ...day20071231.nc How can I do that ? Thank you