Last active
March 4, 2016 15:43
-
-
Save kwilcox/c52155caf5c8c605dca8 to your computer and use it in GitHub Desktop.
Fix floating point precision errors in netCDF time variables
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
import netCDF4 as nc4 | |
from datetime import datetime, timdelta | |
def round_date_time(dt, round_seconds=60): | |
""" | |
modified from: http://stackoverflow.com/questions/3463930/how-to-round-the-minute-of-a-datetime-object-python | |
Round a datetime object to any time laps in seconds, return the | |
timedelta to add to the datetime to round it. | |
dt : datetime object | |
round_seconds : Closest number of seconds to round to, default 1 minute. | |
""" | |
seconds = (dt - dt.min).seconds | |
# '//' is a floor division | |
rounding = (seconds + round_seconds/2) // round_seconds * round_seconds | |
return timedelta(0, rounding - seconds, -dt.microsecond) | |
tvar = nc.variables['time'] | |
tvard = tvar[:] | |
dts = nc4.num2date(tvard, | |
units=tvar.units, | |
calendar=getattr(tvar, 'calendar', 'standard')) | |
add_seconds = np.vectorize(lambda x: round_date_time(x, 60)) | |
tvar[:] = nc4.date2num(dts + add_seconds(dts), | |
units=tvar.units, | |
calendar=getattr(tvar, 'calendar', 'standard')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment