'How to check each date if it's Thursday, if not print the following Thursday [closed]
I have a column of dates in standard date time format. I have to check each date if it's Thursday or not and print if it's Thursday. If it's not then it have to print the following Thursday.
Solution 1:[1]
The following function will print It is Thursday for every Thursday or print the date of the next Thursday for any given date.
import datetime
def next_thursday(date):
# Thursday is day 3 in Python (Monday = 0)
days_ahead = 3 - date.weekday()
if days_ahead == 0:
print("It is Thursday")
# if Thursday has already happened this week we need to add 7 days to the difference
elif days_ahead < 0:
days_ahead += 7
# actually add the time delta using timedelta()
print(date + datetime.timedelta(days=days_ahead), "will be the next Thursday")
date = datetime.datetime.today()
next_thursday(date)
The following is a Python script that will apply abovementioned function to 20 generated random dates in a dataframe column.
def random_date():
today = datetime.datetime.today()
offset = random.randint(0, 100)
return today + datetime.timedelta(days=offset)
dateCol = [random_date() for _ in range(20)]
df = pd.DataFrame({"date": dateCol})
df["date"].apply(next_thursday)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
