以npy/pickle格式保存和加载datetime对象

2024-04-26 21:38:08 发布

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

我试图以分钟为单位计算两个时间戳之间的差值,如果差值大于阈值,我将执行一项任务。到目前为止,我已经尝试做了差异,但它给出了一个错误,因为datetime差异没有给我任何数值

我还需要将第一个datetime对象保存为numpy array/pickle,而不是数据库列,因为这样对我的任务更方便

import datetime
import time

a = datetime.datetime.now() # save this timestamp for later comparison

# save as numpy array

# load the array

time.sleep(100) # program closes, and re-opens

b = datetime.datetime.now()

# comparison in minutes

diff = b-a

# if diff > 60 minutes, do something

if diff > 60:
  pass

我得到的错误是:

---> 20 if diff > 60:
     21   pass
     22 

TypeError: '>' not supported between instances of 'datetime.timedelta' and 'int'

Tags: andimportnumpydatetimeiftimesave错误
1条回答
网友
1楼 · 发布于 2024-04-26 21:38:08

这是您的更新代码

import datetime
import time
import numpy as np

a = datetime.datetime.now() # save this timestamp for later comparison

np_format = np.array([a.year, a.month, a.day, a.hour, a.minute, a.second, a.microsecond]) # all numeric values
np.save('date_old.npy', np_format)

a_load = np.load('date_old.npy')

a_loaded = datetime.datetime(a_load[0], a_load[1], a_load[2], a_load[3], a_load[4], a_load[5], a_load[6])

print(a)

print(a_loaded)

# save as numpy array

# load the array

time.sleep(100) # program closes, and re-opens

b = datetime.datetime.now()

# comparison in minutes

diff = (b-a_loaded).total_seconds()/60.

# if diff > 60 minutes, do something
print(diff)
if diff > 1:
  print('hello')


输出:

2020-04-12 18:14:29.439318
2020-04-12 18:14:29.439318
1.6676882
hello

相关问题 更多 >