Convert julian day into date

user2050187 picture user2050187 · Jun 20, 2013 · Viewed 19.3k times · Source

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

Answer

Dhara picture Dhara · Jun 20, 2013

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.