0

Is there any way to get from a date to the next period? I.e. I am looking for a funaction next that takes

now = datetime.datetime(2013, 11, 15, 0, 0)

to

next(now, 'D') = datetime.datetime(2013, 11, 16, 0, 0) #moving to next day
next(now, 'M') = datetime.datetime(2013,12,31) #moving to next month (day doesn't matter really)

I have tried using Day and MonthEnd from pandas.tseries.offsets but MonthEnd will convert to MonthEnd of the given month, not next month. Is there any simple way to do this?

EDIT: I know this is fairly easy for months. Or days. The problem is, what if I then decide to use business days (Alias 'B')? Or BusinessMonthEnd ('BM')? Surely there should be a method that works for any of these, without having to think about how to implement business days?

Anne
  • 6,752
  • 8
  • 33
  • 50
  • No, there is no such method. And 'next month' is ambigous, what *is* 'next month' from 2013-01-31? – Martijn Pieters Nov 15 '13 at 15:59
  • Take a look at the `dateutil` package, it has a relativedelta object that'll do most of this, including making decisions about the tricky parts. – Martijn Pieters Nov 15 '13 at 15:59
  • Next month from 2013-01-31 should be 2013-02-x. Think about it in periods, i.e. for a monthly period days don't matter. – Anne Nov 15 '13 at 16:00
  • Yet it does matter, because you didn't specify the `x` there. In a leap year, would that be 28 or 29? – Martijn Pieters Nov 15 '13 at 16:02
  • And other processes require adding 30 days, instead of assuming you stay within month boundaries. – Martijn Pieters Nov 15 '13 at 16:03
  • http://stackoverflow.com/a/43663/197657 shows a way to get the number of days in a month, making the rest more or less trivial as they don't vary. – dutt Nov 15 '13 at 16:07

2 Answers2

1

How about using dateutil, like this:

from datetime import date
from dateutil.relativedelta import relativedelta

one_day = date.today() + relativedelta (days =+ 1)
one_month = date.today() + relativedelta( months =+ 1 )
Xar
  • 7,572
  • 19
  • 56
  • 80
0

You should try the timedelta objects.

Finding the next day is pretty easy, as you just have to add 24 hours:

next=now+datetime.timedelta(hours=24)

The next week is simple as well with days=7, but the next month is a bit tricky because a timedelta with days=31 will sometimes fire you two months later.

leeladam
  • 1,748
  • 10
  • 15
  • 1
    Combine with this http://stackoverflow.com/a/43663/197657 and you have everything you need. – dutt Nov 15 '13 at 16:05