我如何在python中解决这个日期时间问题

时间:2016-09-03 05:54:11

标签: python pandas

我是Python和机器学习的新手,我正在尝试解决如何使用日期时间来解决这个问题。 next_unix是13148730,因为这是五个月内的秒数,这是我的约会之间的时间。我搜索过,似乎找不到任何可行的东西。

last_date = df.iloc[1,0]
last_unix = pd.to_datetime('2015-01-31 00:00:00') +pd.Timedelta(13148730)
five_months = 13148730
next_unix = last_unix + five_months  


for i in forecast_set:
     next_date = Timestamp('2015-06-30 00:00:00')
     next_unix += 13148730
     df.loc[next_date] = [np.nan for _ in range(len(df.columns)-1)]+[i]

错误:

  Traceback (most recent call last):

  File "<ipython-input-23-18adaa6b781f>", line 1, in <module>
    runfile('C:/Users/HP/Documents/machine learning.py', wdir='C:/Users/HP/Documents')

  File "C:\Users\HP\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 714, in runfile
    execfile(filename, namespace)

  File "C:\Users\HP\Anaconda3\lib\site-packages\spyderlib\widgets\externalshell\sitecustomize.py", line 89, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "C:/Users/HP/Documents/machine learning.py", line 74, in <module>
    next_unix = last_unix + five_months

  File "pandas\tslib.pyx", line 1025, in pandas.tslib._Timestamp.__add__ (pandas\tslib.c:20118)

ValueError: Cannot add integral value to Timestamp without offset.

2 个答案:

答案 0 :(得分:0)

如果pd.to_datetime返回一个python datetime对象,那么你应该看看你的5个月间隔内使用timedelta对象:

https://docs.python.org/2/library/datetime.html#timedelta-objects

答案 1 :(得分:0)

您可以使用pd.Timedelta()方法:

In [20]: pd.to_datetime('2015-01-31 00:00:00') + pd.Timedelta(seconds=13148730)
Out[20]: Timestamp('2015-07-02 04:25:30')

如果我们尝试为Pandas DateTime添加秒数:

In [22]: pd.to_datetime('2015-01-31 00:00:00') + 13148730
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-22-c252fc51ec14> in <module>()
----> 1 pd.to_datetime('2015-01-31 00:00:00') + 13148730

pandas\tslib.pyx in pandas.tslib._Timestamp.__add__ (pandas\tslib.c:20225)()

ValueError: Cannot add integral value to Timestamp without offset.