【问题标题】:Python - Change UTC to local time in netCDF filePython - 在netCDF文件中将UTC更改为本地时间
【发布时间】:2020-01-27 05:04:50
【问题描述】:

我正在使用来自 ECMWF 的 ERA5 陆地每小时数据,其中包含气候变量。

文件的一般方面是:

'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...

这是一个包含许多变量和观察值的信息矩阵。

在进行任何之前的分析之前,我想使用 Python 将 UTC 时间转换为本地时间 (UTC-5)。我用谷歌搜索并浏览了许多页面和论坛,但我没有找到任何可以回答我的问题的东西。我意识到在一系列帖子中存在命令:

日期时间pytztzinfo时区

以及其他示例,但没有一个示例被视为 netCDF 文件。

提前致谢。

【问题讨论】:

    标签: python-3.x datetime utc netcdf4


    【解决方案1】:

    首先,我建议您省去很多麻烦,并尽可能在 UTC 工作。

    如果您真的需要当地时间,datetimezoneinfo 是您的最佳选择。顺便说一句,转换与netcdf无关,但请记住netCDF4模块提供了有用的功能num2datedate2num[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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-23
      • 2012-03-20
      • 1970-01-01
      • 2021-10-10
      • 1970-01-01
      • 1970-01-01
      • 2018-10-30
      • 2014-03-01
      相关资源
      最近更新 更多