Skip to content Skip to sidebar Skip to footer

Pandas Return The Next Sunday For Every Row

In Pandas for Python, I have a data set that has a column of datetimes in it. I need to create a new column that has the date of the following Sunday for each row. I've tried vari

Solution 1:

Use the Pandas date offsets, e.g.:

>>> pd.to_datetime('2019-04-09') + pd.offsets.Week(weekday=6)
Timestamp('2019-04-14 00:00:00')

For example, this changes the provided datetime over a week. This is vectorised, so you can run it against a series like so:

temp['sunday_dates'] = temp['our_dates'] + pd.offsets.Week(weekday=6)
    our_dates  random_data sunday_dates
0  2010-12-31         4012   2011-01-02
1  2007-12-31         3862   2008-01-06
2  2006-12-31         3831   2007-01-07
3  2011-12-31         3811   2012-01-01

N.b. The Week(weekday=INT) parameter is 0 indexed on Monday and takes values from 0 to 6 (inclusive). Thus, passing 0 yields all Mondays, 1 yields all Tuesdays, etc. Using this, you can make everything any day of the week you would like.

N.b. If you want to go to the last Sunday, just swap + to - to go back.

N.b. (Such note, much bene) The specific documentation on time series functionality can be found here: https://pandas.pydata.org/pandas-docs/stable/user_guide/timeseries.html


Solution 2:

The function

import datetime
def datetime_to_next_sunday(original_datetime):
    return original_datetime + datetime.timedelta(days=6-original_datetime.weekday())

returns the datetime.datetime shifted to the next sunday. Having

import pandas as pd
df = pd.DataFrame({'A': ['Foo', 'Bar'],
                   'datetime': [datetime.datetime.now(),
                                datetime.datetime.now() + datetime.timedelta(days=1)]})

the following line should to the job:

df['dt_following_sunday'] = df[['datetime']].applymap(datetime_to_next_sunday)

Solution 3:

I suggest to use calendar library

 import calendar
 import datetime as dt

 #today date 
 now = datetime.datetime.now()
 print (now.year, now.month, now.day, now.hour, now.minute, now.second)

 # diffrence in days between current date  and  Sunday
 difday =  7 - calendar.weekday(now.year, now.month, now.day)

 # Afterwards next Sunday from today
 nextsunday  = datetime.date(now.year, now.month , now.day + difday)

 print(nextsunday)

Write this function and use


Solution 4:

The accepted answer is the way to go, but you can also use Series.apply() and pandas.Timedelta() for this, i.e.:

df["ns"] = df["d"].apply(lambda d: d + pd.Timedelta(days=(6 if d.weekday() == 6 else 6-d.weekday())))

    d                             ns
0   2019-04-09 21:22:10.886702    2019-04-14 21:22:10.886702

Demo


Post a Comment for "Pandas Return The Next Sunday For Every Row"