在dt.datetime

时间:2017-07-21 19:30:48

标签: python pandas

我有:

excessmove_start = '2015-1-6'

我希望有一个名为excess_graph的新变量,它始终比excessmove_start提前3个月。

因此,对于此示例,我的预期输出将是:

excess_graph = '2015-4-6'

3 个答案:

答案 0 :(得分:2)

这将完成这项工作:

def receive(self, exp_resp, timeout):
    cutoff = datetime.datetime.now() + datetime.timedelta(seconds=timeout)
    serBuffer = ""
    tflag = True  # doesn't seem to be used here -- what is this for??
    while datetime.datetime.now() <= cutoff:
        c = self.port.read()
        serBuffer += c # add to the buffer
        if exp_resp in serBuffer:
            return serBuffer
    return None  # or do you want a partial buffer return after timeout expires?

打印

from datetime import datetime
from dateutil.relativedelta import relativedelta

excessmove_start = '2015-1-6'
s = datetime.strptime(excessmove_start, "%Y-%m-%d")
excess_graph= s+ relativedelta(months=+3)
print(excess_graph.strftime("%Y-%m-%d"))

答案 1 :(得分:1)

s成为看似日期

的样本pd.Series
dates = pd.date_range('2016-01-01', '2016-12-31')
s = pd.Series(np.sort(np.random.choice(dates, 10))).dt.strftime('%Y-%m-%d')
s

0    2016-01-08
1    2016-01-13
2    2016-02-08
3    2016-03-31
4    2016-04-02
5    2016-04-16
6    2016-06-07
7    2016-06-14
8    2016-10-13
9    2016-12-20
dtype: object

您可以使用pd.offsets添加3个月

pd.to_datetime(s) + pd.offsets.DateOffset(months=3)

0   2016-04-08
1   2016-04-13
2   2016-05-08
3   2016-06-30
4   2016-07-02
5   2016-07-16
6   2016-09-07
7   2016-09-14
8   2017-01-13
9   2017-03-20
dtype: datetime64[ns]

您可以将它们转回字符串

(pd.to_datetime(s) + pd.offsets.DateOffset(months=3)).dt.strftime('%Y-%m-%d')

0    2016-04-08
1    2016-04-13
2    2016-05-08
3    2016-06-30
4    2016-07-02
5    2016-07-16
6    2016-09-07
7    2016-09-14
8    2017-01-13
9    2017-03-20
dtype: object

我们可以将它们全部粉碎,以确保一切顺利

xs_start = pd.to_datetime(s)
offset = pd.offsets.DateOffset(months=3)
xs_graph = xs_start + offset

check = pd.DataFrame(dict(
    excessmove_start=xs_start,
    excess_graph=xs_graph,
    delta=xs_graph - xs_start
))

check

    delta excess_graph excessmove_start
0 91 days   2016-04-08       2016-01-08
1 91 days   2016-04-13       2016-01-13
2 90 days   2016-05-08       2016-02-08
3 91 days   2016-06-30       2016-03-31
4 91 days   2016-07-02       2016-04-02
5 91 days   2016-07-16       2016-04-16
6 92 days   2016-09-07       2016-06-07
7 92 days   2016-09-14       2016-06-14
8 92 days   2017-01-13       2016-10-13
9 90 days   2017-03-20       2016-12-20

答案 2 :(得分:0)

使用relativedelta

import dateutil

excessmove_start = date(2015,1,6)
excess_graph = excessmove_start + datetime.relativedelta.relativedelta(months=3))