甚至有幾篇關于 NetCDF 檔案和時間戳轉換的帖子我今天還是一片空白。
我讀入了一個 NetCDF 資料集(版本 3),在呼叫變數資訊之后:
# Load required Python packages
import netCDF4 as nc
import matplotlib.pyplot as plt
from datetime import datetime, timedelta
import pandas as pd
#read in a NetCDF data set
ds = nc.Dataset(fn)
# call time variable information
print(ds['time'])
作為答案,我得到:
<class 'netCDF4._netCDF4.Variable'>
float64 time(time)
units: seconds since 1904-01-01 00:00:00.000 00:00
long_name: time UTC
axis: T
unlimited dimensions: time
current shape = (5760,)
filling on, default _FillValue of 9.969209968386869e 36 used
現在我想將自 1.1.1904 時間戳以來的秒數轉換為 DD.MM.YYYY HH:MM:SS.sss 格式。(順便問一下:為什么在時間戳之后包含第二個 00:00 資訊?)
(1)我試過:
t = ds['time'][:]
dtime = []
dtime = (pd.to_datetime(t, format='%d.%m.%Y %H:%M:%S.micros') - datetime(1904, 1, 1)).total_seconds()
我得到錯誤:pandas_libs\tslibs\strptime.pyx in pandas._libs.tslibs.strptime.array_strptime() 時間資料 '3730320000' 與格式 '%d.%m.%Y %H:%M:% 不匹配S'(匹配)
(2)我試過:
d = datetime.strptime("01-01-1904", "%m-%d-%Y")
dt = d timedelta(seconds=(t))
我得到 TypeError: unsupported type for timedelta seconds component: MaskedArray
(3) 我試過了
d = datetime.strptime("%m-%d-%Y", "01-01-1904")
dt = d timedelta(seconds=(ds['time']))
我得到了答案:timedelta seconds 組件不受支持的型別:netCDF4._netCDF4.Variable
有人比我現在對解決方案有更清晰的看法嗎?
謝謝, 斯瓦瓦
uj5u.com熱心網友回復:
NetCDF4 python 庫有一個方法:num2date().
https://unidata.github.io/netcdf4-python/#num2date。不需要datetime模塊。
NetCDF4 變數包含元資料屬性,這些屬性描述了在您的列印輸出中看到的變數:
print(ds['time'])#特別是時間變數units屬性。
# t contains just the numeric values of the time in `seconds since 1904-01-01 00:00:00.000 00:00`
t = ds['time'][:]
dtime = []
# t_var is the NetCDF4 variable which has the `units` attribute.
t_var = ds.['time']
#dtime = (pd.to_datetime(t, format='%d.%m.%Y %H:%M:%S.micros') - datetime(1904, 1, 1)).total_seconds()
dtime = NetCDF4.num2date(t, t_var.units)
上面應該給你dtime串列中的所有時間作為日期時間物件。
print(dtime[0].isoformat())
print(dtime[-1].isoformat())
一個更簡單的方法是:
dtime = NetCDF4.num2date(ds['time'][:], ds['time].units)
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/472605.html
標籤:python-3.x 约会时间 netcdf
上一篇:決議可怕的時間戳C#
