Convert julian day into date

非 Y 不嫁゛ 提交于 2019-11-30 19:28:57

问题


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


回答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.




回答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')



回答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.



来源:https://stackoverflow.com/questions/17216169/convert-julian-day-into-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!