Reputation: 13
I tried this code but it's only giving me the current day name.
How can I get the next day name?
import datetime
d = datetime.datetime.now()
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
a = days[d.weekday()]
Upvotes: 1
Views: 1001
Reputation: 16486
First add one day to your date with timedelta
object, then get the name of the day with strftime('%A')
.
import datetime
next_day = datetime.datetime.now() + datetime.timedelta(days=1)
print(next_day.strftime('%A'))
That's it. There is no need to have extra days
list and use the index (d.weekday() + 1
), but if you want to do that, you should also use %
operator(@Anentropic mentioned here) to prevent IndexError
when your day is "Sunday". In that case .weekday()
will return 6
and the days[d.weekday() + 1]
will raise an exception.
Upvotes: 1
Reputation: 33833
We can use the modulo operator %
to wraparound our lookup in the days list:
import datetime
d = datetime.datetime.now()
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
today_name = days[d.weekday()]
tomorrow_name = days[(d.weekday() + 1) % 7]
https://docs.python.org/3.3/reference/expressions.html#binary-arithmetic-operations
Upvotes: -1
Reputation: 1130
import datetime
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
Just get the next number in the array because the current day get the current:
d = datetime.datetime.now()
# Monday
a = days[d.weekday()+1]
# Tuesday
Upvotes: -1
Reputation: 43972
No need for a hardcoded array, use strftime()
import datetime
tomorrow = datetime.date.today() + datetime.timedelta(days=1)
print(tomorrow.strftime('%A'))
# Wednesday
Upvotes: 1
Reputation: 4707
The first step: calculate tomorrow day. Second step: get the name of tomorrow's day
import datetime
d = datetime.datetime.now()
tomorrow = d + datetime.timedelta(days=1)
days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
a = days[tomorrow.weekday()]
Upvotes: 1
Reputation: 11414
You can add a number of days to a given date to produce a new datetime
object for that date:
tomorrow = d +datetime.timedelta(days=1)
print(days[d.weekday()])
Upvotes: 1
Reputation: 2406
You can use strftime:
(d + datetime.timedelta(1)).strftime('%A')
>>> 'Wednesday'
Upvotes: 3