[英]Convert time decimal to datetime object python
我试图将十进制时间转换为日期时间对象以查找月份,以便以后将时间划分为季节。 我做了一些研究,偶然发现了datetime.datetime.fromtimestamp,但是我尝试的所有操作都会产生以下错误:
TypeError: 'datetime.datetime' object is not iterable
过去,我曾使用熊猫来创建新的时间序列,但并不觉得这对我的情况是最好的。 目前,我的代码中包含以下内容,并尝试在不使用for循环的情况下进行操作,以希望fromtimestamp()能够正常工作。
raw_time = (data.variables['time'].getValue()/float(365*24))+1800 #hours since 1800
time = n.where((raw_time>=2006)&(time<=2016)) #our specific time interval
annual_time = []
for i in raw_time[time]:
annual_time.extend(datetime.datetime.fromtimestamp(i))
我的时间是作为netCDF文件读取的,当前显示如下:
print raw_time[time]
array([ 2006.05205479, 2006.1369863 , 2006.22191781, 2006.29863014,
2006.38356164, 2006.46575342, 2006.55068493, 2006.63287671,
2006.71780822, 2006.80273973, 2006.88493151, 2006.96986301,
2007.05205479, 2007.1369863 , 2007.22191781, 2007.29863014,
2007.38356164, 2007.46575342, 2007.55068493, 2007.63287671,
2007.71780822, 2007.80273973, 2007.88493151, 2007.96986301,
2008.05205479, 2008.1369863 , 2008.22191781, 2008.30136986,
2008.38630137, 2008.46849315, 2008.55342466, 2008.63561644,
2008.72054795, 2008.80547945, 2008.88767123, 2008.97260274, ...])
该错误信息是由于您使用了extend
:
annual_time = []
for i in raw_time[time]:
annual_time.extend(datetime.datetime.fromtimestamp(i))
list .extend()
用于获取另一个列表或可迭代列表,并将其内容添加到列表末尾。 datetime
不返回列表或不可迭代; 它返回一个datetime实例。 对于标量值,您需要使用append
:
annual_time = []
for i in raw_time[time]:
annual_time.append(datetime.datetime.fromtimestamp(i))
话虽如此,我认为您需要在使用此功能之前对时间值进行操作,因为您提供的值看起来不像时间戳(时间戳是经过UTC 1970年1月1日00:00:00的秒数) -除非那些时间真的应该在1970年1月1日午夜之后约半小时...
您应该使用netCDF4 num2date将time
从数字值转换为datetime对象。
import netCDF4
ncfile = netCDF4.Dataset('./foo.nc', 'r')
time = ncfile.variables['time'] # do not cast to numpy array yet
time_convert = netCDF4.num2date(time[:], time.units, time.calendar)
例如,这将创建一个time_convert
对象的time_convert
数组,您可以使用time_convert
数组来生成季节。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.