Brian
Brian

Reputation: 87

Python - Change UTC to local time in netCDF file

I'm working with ERA5 land hourly data from ECMWF, which contains climatic variables.

The general aspect of the file is:

'era5-hourly-2m_temperature_firstfourdays-january_2017.nc'

Dimensions:    (latitude: 184, longitude: 129, time: 96)
Coordinates:
  * longitude  (longitude) float32 -81.4 -81.3 -81.2 -81.1 ... -68.8 -68.7 -68.6
  * latitude   (latitude) float32 -0.1 -0.2 -0.3 -0.4 ... -18.2 -18.3 -18.4
  * time       (time) datetime64[ns] 2017-01-01 ... 2017-01-04T23:00:00
Data variables:
    t2m        (time, latitude, longitude) float32 ...
Attributes:
    Conventions:  CF-1.6
    history:      2020-01-09 19:38:29 GMT by grib_to_netcdf-2.15.0: /opt/ecmw...

This is a matrix of information which contains many variables and observations.

Before any previous analysis, I want to convert UTC time to local time (UTC-5) using Python. I googled and surfed many pages and forums but I did not find anything that answers to my question. I realized the presence of the commands in a range of posts:

datetime, pytz, tzinfo, astimezone,

and others but none of the examples considered a netCDF file.

Thanks in advance.

Upvotes: 1

Views: 1560

Answers (1)

FObersteiner
FObersteiner

Reputation: 25564

First of all, I'd suggest to save yourself a lot of trouble and work in UTC whenever possible.

If you really need a local time, datetime and zoneinfo are your way to go. By the way, the conversion has nothing to do with netcdf, but remember that the netCDF4 module offers helpful functions num2date and date2num [docs].

from datetime import datetime, timezone
from zoneinfo import ZoneInfo # Python 3.9+

string = '2017-01-04T23:00:00'
dt_obj = datetime.fromisoformat(string)

# note that dt_obj is naive, i.e. it has no timezone info, so let's add it:
dt_obj = dt_obj.replace(tzinfo=timezone.utc)
print(datetime.strftime(dt_obj, '%Y-%m-%dT%H:%M:%S %Z %z'))
# 2017-01-04T23:00:00 UTC +0000

# now let's shift time to another timezone:
new_timezone = ZoneInfo('US/Eastern')
dt_obj = dt_obj.astimezone(new_timezone)
print(datetime.strftime(dt_obj, '%Y-%m-%dT%H:%M:%S %Z %z'))
# 2017-01-04T18:00:00 EST -0500

Upvotes: 2

Related Questions