如何初始化并附加到datetime类型的数组?

2024-10-02 12:33:27 发布

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

问题是初始化Datetime类型的空数组,在for循环中将datetime类型的值附加到该数组中,然后选择在特定范围内的值。你知道吗

我有一个脚本,它将纬度(chla, 'numpy.ndarray')、经度(chlo, 'numpy.ndarray')和世界时(chtime, 'numpy.ndarray')作为输入。然后计算时区偏移量(datetime.timedelta)和本地时间。你知道吗

最终输出的位置应介于08:00-16:00 LT之间

timezone.utcoffset(dt)+chtime[i]是正确的类型(datetime.datetime),但是在附加到本地时间数组之后,它就变成了类型list。你知道吗

我试着将它声明为numpy数组,dtype=datetimelocal_time = np.datetime64([])的numpy数组

编辑:在indicest = np.where((local_time >= start) & (local_time <=end))之前添加local_time = np.array(local_time)

错误现在显示:

TypeError: '>=' not supported between instances of 'datetime.datetime' and 'datetime.time'
import numpy as np
import datetime
import pytz
from timezonefinder import TimezoneFinder

tf = TimezoneFinder()
start = datetime.time(hour=8, minute=0)
end = datetime.time(hour=16, minute=0)  
local_time = []

for i in range(0, np.size(chtime)):

     anotherObj = tf.closest_timezone_at(lng=chlo[i], lat=chla[i], delta_degree=10)  
     timezone = pytz.timezone(anotherObj)
     dt = datetime.datetime.now()        
     local_time.append(timezone.utcoffset(dt)+chtime[i])    

indicest = np.where((local_time >= start) & (local_time <=end))

预期输出为08:00和16:00之间位置的索引列表,但收到以下错误消息:

indicest = np.where((local_time >= start) & (local_time <=end))

'>=' not supported between instances of 'list' and 'datetime.time'

Tags: importnumpy类型datetimetimelocalnpdt
1条回答
网友
1楼 · 发布于 2024-10-02 12:33:27

找到了一个解决方案,尽管不是我想要的格式。而是将本地时间设为变量,并在for循环中添加if语句:

    for i in range(0, np.size(indicesla)): 

        anotherObj = tf.closest_timezone_at(lng=chlo[i], lat=chla[i], delta_degree=10)  
        timezone = pytz.timezone(anotherObj)
        dt = datetime.datetime.now()    
        local_time = chtime[i] + timezone.utcoffset(dt)

        if start <= local_time.time() <= end:
            newchla[n] = chla[i]
            newchlo[n] = chlo[i]
            chtime[n] = local_time
            n = n+1

    return newchla, newchlo

它很重,但很有效:/

相关问题 更多 >

    热门问题