bash 将儒略日转换为日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17216169/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Convert julian day into date
提问by user2050187
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
我有好几年名为 day00000.nc、day00001.nc、day00002.nc、...day00364.nc 的文件。它们代表 365 或 366 天。我想像这样重命名我的文件 day20070101.nc, day20070102.nc, ...day20071231.nc 我该怎么做?谢谢
回答by Dhara
Use the datetimemodule 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 2007in the code with a variable if required.
使用datetime模块从一年中的某一天获取日期。我假设年份是 2007,如您的示例中所示,因为您的文件名似乎没有年份值。2007如果需要,可以随意用变量替换代码中的硬编码。
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.
OP 的文件编号为 0 到 364,而不是 1 到 365。此解决方案适用于 OP。如果您的日期是从 1 到 365,并且对您来说一点也不明显,请在将其转换为 timedelta 值之前自由地从 day 变量中减去“1”。
回答by cmd
datetimehas a build in julian converter in it's strptimefunction using the %jformat specifier. Assuming that your files are 'day'two digit year + julian + extention (if not, just add whatever year offset you really have)
datetimestrptime使用%j格式说明符在其功能中内置了朱利安转换器。假设您的文件是'day'两位数的年份 + 朱利安 + 扩展名(如果不是,只需添加您真正拥有的任何年份偏移量)
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')
回答by Ed Morton
With GNU awk and any Bourne-like shell
使用 GNU awk 和任何类似 Bourne 的 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.
测试后删除“回声”。

