【问题标题】:How to add hours onto Day of Year如何将小时数添加到一年中的某一天
【发布时间】:2017-12-12 21:46:27
【问题描述】:

我正在使用 Python 处理海洋学数据。我目前正在尝试在 x 轴上创建时间等高线图,在 y 轴上创建压力,以及温度作为等高线。现在我正在尝试使用从数据本身获得的值来格式化时间数组。我的代码只生成一年中的某一天,而没有添加相应的时间。我需要一种方法来增加每天 6 小时、12 小时和 18 小时,因为数据来自每天运行 4 次的水柱剖面图,相隔 6 小时。共有 1260 个配置文件,i 对应于每个配置文件的文件。

import numpy
from matplotlib import pyplot as plt
import math
from datetime import tzinfo, timedelta, datetime, time
import time

i = 1
temp = numpy.zeros((1260, 1000))
pressure = numpy.zeros((1260, 1000))
time2 = numpy.zeros(1260)
for i in range(1, 1260):
    filename = '/Users/ryanschubert/InternProject/itp47final/itp47grd' + str(i).zfill(4) + '.dat'
    if os.path.isfile(filename):
        data = open(filename, "r")
    else:
        continue
    depthcounter=-1
    text = data.read()
    data.close()
    text = text.replace('   ', ',')  #this line and the next 5 lines are 
    text = text.replace('  ', ',')   #fixing formatting errors in the code
    text = text.replace(' ', '')
    text = text.replace('NaN', '-98')
    text = text.replace(',,', ',')
    text = text.split('\n')
    for line in text:
        depthcounter=depthcounter+1
        if depthcounter == 1:
            if i ==1:
                words4 = line.split(',')
                year = int(words4[0])
                doy = float(words4[1]) - 1
                hour = int((doy - math.floor(doy))*24)
                t = datetime(year=year, month=1, day=1, hour=hour,tzinfo=utc) + timedelta(days=int(doy))
                time1 = t.timetuple().tm_yday
                timetemp = numpy.array([t + timedelta(days=j/4.) for j in xrange(1260)])
            else:
                time2[i] = timetemp[i].timetuple().tm_yday
                print(time2[i])`

代码当前返回这样的值;

102
102.0
102.0
103.0
103.0
103.0
103.0
104.0
104.0
104.0
104.0
105.0
105.0
105.0
105.0
106.0
106.0
106.0
106.0
107.0
107.0
107.0
107.0

等等……

我需要帮助将一年中的前一天增加 6 小时,以便数组看起来像-

102
102.25
102.5
102.75
103.0
103.25
103.5
103.75
104.0

等等。

【问题讨论】:

  • 什么是i?这是在函数内部吗?如果是这样,您是如何应用该功能的?

标签: python python-3.x datetime contourf


【解决方案1】:

您可以添加timedelta(hours=6),而不是添加1/4. 天的timedelta。

否则,既然您知道您希望时间以0.25 为增量增加,您可以简单地从一开始就生成一个浮点数组。

请注意,在我的 python3 版本中,timetuple().tm_yday 返回一个整数,而不是浮点数。

【讨论】:

    猜你喜欢
    • 2018-03-27
    • 1970-01-01
    • 1970-01-01
    • 2015-04-27
    • 2021-02-06
    • 1970-01-01
    • 2014-08-03
    • 2013-03-25
    • 2012-03-27
    相关资源
    最近更新 更多