Skip to content

Commit

Permalink
Fix converting other DateTime objects to seconds
Browse files Browse the repository at this point in the history
  • Loading branch information
ph-kev committed Oct 18, 2024
1 parent 961cdac commit b967146
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 3 deletions.
1 change: 1 addition & 0 deletions NEWS.md
Original file line number Diff line number Diff line change
Expand Up @@ -61,6 +61,7 @@ ClimaAnalysis.replace(var, NaN => 0.0, missing => 0.0)
if duplicate dates are detected.
- Fix issue with plotting multiple figures at the same time.
- Improve shading for `Visualize.heatmap2D_on_globe!`.
- Add support for automatically converting CFTime.AbstractCFDateTime dates to seconds.

v0.5.10
-------
Expand Down
17 changes: 14 additions & 3 deletions src/Var.jl
Original file line number Diff line number Diff line change
Expand Up @@ -226,7 +226,12 @@ function OutputVar(
)
var = read_var(path; short_name)
# Check if it is possible to convert dates to seconds in the time dimension
if (has_time(var) && eltype(times(var)) <: Dates.DateTime)
if (
has_time(var) && (
eltype(times(var)) <:
Union{Dates.DateTime, NCDatasets.CFTime.AbstractCFDateTime}
)
)
var = _dates_to_seconds(
read_var(path; short_name),
new_start_date = new_start_date,
Expand Down Expand Up @@ -1496,11 +1501,17 @@ function _dates_to_seconds(
has_time(var) || error(
"Converting from dates to seconds is only supported for the time dimension",
)
eltype(times(var)) <: Dates.DateTime ||
eltype(times(var)) <:
Union{Dates.DateTime, NCDatasets.CFTime.AbstractCFDateTime} ||
error("Type of time dimension is not dates")

# Preprocess time_arr by shifting dates
# Reinterpret everything as DateTime.Dates
time_arr = copy(times(var))
if eltype(time_arr) <: NCDatasets.CFTime.AbstractCFDateTime
time_arr = map(t -> reinterpret(Dates.DateTime, t), time_arr)
end

# Preprocess time_arr by shifting dates
if !isnothing(shift_by)
time_arr .= shift_by.(time_arr)
end
Expand Down
Binary file added test/sample_nc/test_gpp.nc
Binary file not shown.
11 changes: 11 additions & 0 deletions test/test_Var.jl
Original file line number Diff line number Diff line change
Expand Up @@ -1410,6 +1410,17 @@ end
@test ClimaAnalysis.times(file_var) == [0.0, 1398902400.0]
@test file_var.attributes["start_date"] == "1979-01-01T00:00:00"

# Test constructor for DateTimeNoLeap for the type of the time dimension
ncpath = joinpath(@__DIR__, "sample_nc/test_gpp.nc")
file_var = ClimaAnalysis.OutputVar(
ncpath,
"gpp";
new_start_date = nothing,
shift_by = identity,
)
@test ClimaAnalysis.times(file_var) == [0.0]
@test file_var.attributes["start_date"] == "1980-01-15T00:00:00"

# Test for error handling
# Use date dimension instead of time dimension
date_arr = [
Expand Down

0 comments on commit b967146

Please sign in to comment.