将时间十进制转换为datetime对象python

2024-05-18 23:08:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图将十进制时间转换为datetime对象来查找月份,以便稍后将时间划分为季节。我做了一些研究,偶然发现datetime.datetime.fromtimestamp但我所做的一切都会产生以下错误:

                 TypeError: 'datetime.datetime' object is not iterable

过去,我曾用熊猫来创建一个新的时间序列,但不觉得这对我的特定情况是最好的。目前,我的代码中有以下代码,并尝试在不使用for循环的情况下执行此操作,希望能够使fromtimestamp()正确工作。在

^{pr2}$

我的时间是从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, ...])

Tags: 对象代码datetimeobjecttimeis错误时间
2条回答

错误消息是由于您使用了extend

annual_time = []
for i in raw_time[time]:
    annual_time.extend(datetime.datetime.fromtimestamp(i))

listlist.extend()用于获取另一个list或iterable,并将其内容添加到列表的末尾。datetime不返回list或iterable;它返回一个datetime实例。对于标量值,您需要使用append

^{pr2}$

话虽如此,我认为在使用此函数之前,您需要操作时间值,因为您提供的值看起来不像时间戳(时间戳是指1970年1月1日00:00:00 UTC之后的几秒钟),除非这些时间真的应该是在1970年1月1日午夜后半小时左右。。。在

您应该使用netCDF4 num2date将{}从数值转换为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_convertdatetime对象数组,然后可以使用该数组生成季节。在

相关问题 更多 >

    热门问题