|
| 1 | +#!/usr/bin/perl |
| 2 | + |
| 3 | +## This script converts a date string to the corresponding time for a |
| 4 | +## given netcdf file by using the NCL function ut_inv_calendar. |
| 5 | + |
| 6 | +$usage = "Usage: date2time netcdf-file yyyy-mm-dd [hh:mm]\n"; |
| 7 | + |
| 8 | + |
| 9 | +if (@ARGV < 2 or @ARGV > 3) { |
| 10 | + die $usage; |
| 11 | +} |
| 12 | + |
| 13 | +$file = $ARGV[0]; |
| 14 | + |
| 15 | +($year, $month, $day) = split /[-\/]/, $ARGV[1]; |
| 16 | + |
| 17 | +($hour, $minute, $second) = split /\:/, $ARGV[2]; |
| 18 | + |
| 19 | +$hour += 0; |
| 20 | +$minute += 0; |
| 21 | +$second += 0; |
| 22 | + |
| 23 | +# Check for numeric validity |
| 24 | + |
| 25 | +if ($year !~ /\d{4}/ or |
| 26 | + $month < 0 or $month > 12 or |
| 27 | + $day < 0 or $day > 31 or |
| 28 | + $hour < 0 or $hour > 24 or |
| 29 | + $minute < 0 or $minute > 60 or |
| 30 | + $second < 0 or $second > 60){ |
| 31 | + die "Invalid date specification: $year/$month/$day $hour:$minute:$second (should be YYYY/MM/DD [hh:mm:ss])\n"; |
| 32 | +} |
| 33 | + |
| 34 | + |
| 35 | +$units = `ncdump -h $file | grep time:units | cut -f 2 -d \\\"`; |
| 36 | +unless ($units) {die "No units found in netcdf file $file.\n";} |
| 37 | + |
| 38 | +$calendar = `ncdump -h $file | grep time:calendar | cut -f 2 -d \\\"`; |
| 39 | +unless ($calendar) {die "No calendar found in netcdf file $file.\n";} |
| 40 | + |
| 41 | +chomp $units; |
| 42 | +chomp $calendar; |
| 43 | + |
| 44 | +$tempfile = ".date2time.$$"; |
| 45 | + |
| 46 | +open(NCL, ">$tempfile"); |
| 47 | + |
| 48 | + |
| 49 | +$nclscript = <<END; |
| 50 | +c = 0 |
| 51 | +c\@calendar = \"$calendar\" |
| 52 | +date = cd_inv_calendar($year,$month,$day,$hour,$minute,$second,\"$units\",c) |
| 53 | +print(sprintf("%.4f",date)) |
| 54 | +END |
| 55 | + |
| 56 | + print NCL "$nclscript"; |
| 57 | + |
| 58 | +close(NCL); |
| 59 | + |
| 60 | +$result = `ncl -n -Q $tempfile`; |
| 61 | +print "$result"; |
| 62 | + |
| 63 | +`rm $tempfile`; |
| 64 | + |
| 65 | +# Copyright 2010-2012 Univ. Corp. for Atmos. Research |
| 66 | +# Author: Seth McGinnis, [email protected] |
0 commit comments