问题描述
我有一个名为day00000.nc,day00001.nc,day00002.nc,... day00364.nc几年来的文件。
他们重新present 365或366天。
我想重新命名我的文件这样day20070101.nc,day20070102.nc,... day20071231.nc
我该怎么办呢?
谢谢
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.ncHow can I do that ? Thank you
推荐答案
使用模块得到一年中的哪一天日期。我假设年份是2007年在你的例子,因为你的文件名似乎并不有一个年份。随时与如果需要一个变量来代替硬codeD 2007
在code。
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
对于那些因为该解决方案增加了一天谁是downvoting这个答案
该任择议定书的文件编号为0至364,而不是1到365此解决方案的OP。如果您的日期是从1到365,这不是在所有明显的给你,请把它转换为timedelta值之前freel自由地从白天变减1。
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.
这篇关于转换儒略日为日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!