Generating dates to the days of a week in Python? - python

I need to generate a date of Monday of a week from a date (example: 2015/10/22). And generate the dates for the next days: Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, Sunday.
Example in Java: (initial date = 2015/10/22)
// Monday:
date.set (Calendar.DAY_OF_WEEK, Calendar.MONDAY);
// Add the next day (Tuesday)
date.add (Calendar.DATE, 1);
// Add the next day (Wednesday):
date.add (Calendar.DATE, 1);
How can I do this in Python?

Its easier in python using timedelta function
import datetime
mydate = datetime.datetime(2015, 10, 22, 00, 00, 00, 00)
mymondaydate = mydate - datetime.timedelta(days=mydate.weekday())
mytuesdaydate = mymondaydate + datetime.timedelta(days=1)
print(mydate)
print(mymondaydate)
print(mytuesdaydate)
The trick is the use of weekday() function. From documentation
date.weekday()
- Return the day of the week as an integer, where Monday is 0 and Sunday is 6.
So subtracting it from current date gives the date of Monday of that week

You can set your initial date like this:
from datetime import datetime, timedelta
d = datetime(2015,10,22)
Then if you want to get the next monday, use timedelta and datetime.weekday() (Monday is 0):
d + timedelta(7 - d.weekday())
datetime.datetime(2015, 10, 26, 0, 0)

Provide another version for your question.
You can refer the document of official site: datetime, time
from datetime import date
from datetime import timedelta
import time
t = time.strptime('2015/10/22', '%Y/%m/%d')
old_day = date.fromtimestamp(time.mktime(t))
a_day = timedelta(days=1)
new_day = old_day + a_day
print new_day.strftime('%a')

Related

How to get last Thursday date of next month and next of next month using python

I want to get Date on Last Thursday of next month and next of next month.
Currently able to get Date of last thursday on current month.
Code:
import datetime
dt = datetime.datetime.today()
def lastThurs_currentmonth(dt):
currDate, currMth, currYr = dt, dt.month, dt.year
for i in range(31):
if currDate.month == currMth and currDate.year == currYr and currDate.weekday() == 3:
#print('dt:'+ str(currDate))
lastThuDate = currDate
currDate += datetime.timedelta(1)
return lastThuDate
lastThurs_currentmonth(dt)
Output:
datetime.datetime(2022, 11, 24, 11, 2, 17, 620842)
Now I need to get date last Thursday for next month and next of next month.
Expected Output:
date last Thursday for next month
datetime.datetime(2022, 12, 29)
date last Thursday for next of next month
datetime.datetime(2023, 1, 26)
Ref link:
Get the last thursday of the current month using python
One way is to add months less one day from the start of the current month and then subtract back to the last Thursday. Thursdays are isoweekday 4, so it's a case of subtracting off the right number of days. Unfortunately timedelta doesn't allow months, so the dateutil library is also needed for my solution.
import datetime
from dateutil.relativedelta import relativedelta
def last_thrs(start_date, months):
date_to_check = datetime.date(start_date.year, start_date.month, 1) + relativedelta(months=months+1) - datetime.timedelta(days=1)
return date_to_check - datetime.timedelta(days = ((date_to_check.isoweekday() + 3) % 7))
dt_today = datetime.date.today()
print(last_thrs(dt_today, 1))
# 2022-12-29

Python construct datetime having weekday with other time parameters

I need to construct datetime object from different parameters. For example, I get these parameters:
integer number from 0 to 6. This one indicates weekday.
hour and minutes in float format (from 0.0 to 24.0).
And then I know which week of the current year it is going to be. So, for example, let say that datetime should be from 2014-07-18 00:00:00 to 2014-07-24 23:59:00 (seconds can be ignored and left at 00). So to get exact datetime I need to use above defined parameters.
Let say I would get these parameters 4 (meaning Friday), and 9.5 (meaning 09:30).
So by doing such construction, I should get a date that would be: 2014-07-22 09:30:00. How could accomplish such thing?
Do I need to somehow get for example day of the month by knowing which is the week of the year and which weekday it is?
P.S. A bit more detailed example of what I'm trying to accomplish
from datetime import datetime
today = datetime.today() #using this to get the week I'll be working with.
today = today.replace(day=?) #how to get which day I
#need to enter by having weekday and knowing that week is the present one?
You could do something like that, if your parameters are weekday and t (time):
from datetime import timedelta
monday = today - timedelta(days=today.weekday())
result = (monday + timedelta(days=weekday)).replace(hour=int(t), minutes=int((t - int(t)) * 60))
If you have a starting date, use the relative value of the datetime.datetime.weekday() value to construct a timedelta() object that'll put you onto the right weekday, then replace the hour and minutes:
from datetime import timedelta
def relative_date(reference, weekday, timevalue):
hour, minute = divmod(timevalue, 1)
minute *= 60
days = reference.weekday() - weekday
return (reference - timedelta(days=days)).replace(
hour=int(hour), minute=int(minute), second=0, microsecond=0)
Demo:
>>> from datetime import timedelta, datetime
>>> def relative_date(reference, weekday, timevalue):
... hour, minute = divmod(timevalue, 1)
... minute *= 60
... days = reference.weekday() - weekday
... return (reference - timedelta(days=days)).replace(
... hour=int(hour), minute=int(minute), second=0, microsecond=0)
...
>>> relative_date(datetime.now(), 4, 9.5)
datetime.datetime(2014, 8, 22, 9, 30)
>>> relative_date(datetime.now() - timedelta(days=30), 6, 11.75)
datetime.datetime(2014, 7, 27, 11, 45)
I would use timedelta to add the difference between weekdays to the datetime
from datetime import datetime, timedelta
friday = 4
today = datetime.now()
friday_this_week = today + timedelta(friday - today.weekday())
In your case just replace today with a date that is in the week you want.

Python: get last Monday of July 2010

How do I get the last Monday (or other day) of a given month?
Have a look at dateutil:
from datetime import datetime
from dateutil import relativedelta
datetime(2010,7,1) + relativedelta.relativedelta(day=31, weekday=relativedelta.MO(-1))
returns
datetime.datetime(2010, 7, 26, 0, 0)
Using the calendar module from the stdlib:
import calendar
cal = calendar.Calendar(0)
month = cal.monthdatescalendar(2010, 7)
lastweek = month[-1]
monday = lastweek[0]
print(monday)
2010-07-26
Based on Gary's answer :
import calendar
month = calendar.monthcalendar(2010, 7)
mondays = [week[0] for week in month if week[0]>0]
print mondays[-1]
26
This works for getting the last Sunday of the month even if the last week of the month has no Sunday.
A tiny improvement on manu's answer !
import calendar
month = calendar.monthcalendar(2010, 7)
day_of_month = max(month[-1][calendar.SUNDAY], month[-2][calendar.SUNDAY])
print day_of_month

Previous weekday in Python

In Python, given a date, how do I find the preceding weekday? (Weekdays are Mon to Fri. I don't care about holidays)
Simply subtract a day from the given date, then check if the date is a weekday. If not, subtract another, until you do have a weekday:
from datetime import date, timedelta
def prev_weekday(adate):
adate -= timedelta(days=1)
while adate.weekday() > 4: # Mon-Fri are 0-4
adate -= timedelta(days=1)
return adate
Demo:
>>> prev_weekday(date.today())
datetime.date(2012, 8, 20)
>>> prev_weekday(date(2012, 8, 20))
datetime.date(2012, 8, 17)
Alternatively, use an offset table; no need to make this a mapping, a tuple will do just fine:
_offsets = (3, 1, 1, 1, 1, 1, 2)
def prev_weekday(adate):
return adate - timedelta(days=_offsets[adate.weekday()])
This is an old question, but anyway, a simpler way to do that, which doesn't require loops
from datetime import datetime, timedelta
today = datetime.today() # Today date
weekday = 6
days = today.isoweekday() - weekday
if days<0:
days += 7
previous_date = today - timedelta(days=days)
print(previous_date)
See the datetime module, in particular the date() and weekday() function. For example:
import datetime
temp = datetime.date(2012,8,21) # Today's date: 2012/08/21
print temp.weekday()
This will output 1. 0 stands for Monday, 1 for Tuesday, etc., until 6 for Sunday. Finding the preceding weekday is easy from here.
in datetime module you can do something like this: a = date.today() - timedelta(days=1)
and then a.weekday(). Where monday is 0 and sunday is 6.

Find the Friday of previous/last week in python

Eg1. Suppose I have a day 4/30/07 .Then I need to get 4/27/07.
Eg2. Suppose I have a day 6/29/07 .Then I need to get 6/22/07.
Assuming day is a datetime.date or datetime.datetime object, this code creates a datetime/date object for last week's friday:
friday = day - timedelta(days=day.weekday()) + timedelta(days=4, weeks=-1)
Explanation: timedelta(days=day.weekday()) is the offset between monday and day so adding 4 days and subtracting one week will get you last week's friday.
Of course you can simplify this (+4d -1w = -3d):
friday = day - timedelta(days=day.weekday() + 3)
Note: To get timedelta, use from datetime import timedelta or just import datetime and use datetime.timedelta
An another and easier way is to use python-dateutil.
To get the previous Friday :
>>> from dateutil.relativedelta import relativedelta, FR
>>> from datetime import datetime
>>> datetime(2015, 7, 8) + relativedelta(weekday=FR(-1))
datetime.datetime(2015, 7, 3, 0, 0)
And the next Friday :
>>> datetime(2015, 7, 8) + relativedelta(weekday=FR(+1))
datetime.datetime(2015, 7, 10, 0, 0)
Not specific to Friday, but given a day "taget_dayofweek" (where Monday is 0 and Sunday is 6)
from datetime import datetime
target_dayofweek = 4 # Friday
current_dayofweek = datetime.now().weekday() # Today
if target_dayofweek <= current_dayofweek:
# target is in the current week
endDate = datetime.now() - timedelta(current_dayofweek - target_dayofweek)
else:
# target is in the previous week
endDate = datetime.now() - timedelta(weeks=1) + timedelta(target_dayofweek - current_dayofweek)
There are plenty of options in pandas.tseries.offsets
This one is for previous week friday.
from pandas.tseries.offsets import Week
f_dates = required_df.index - Week(1, weekday=4)
date_object = datetime.date.today()
from dateutil.relativedelta import relativedelta
previousWeekLastDay = date_object + relativedelta(weekday=SU(-1))
previousWeekFirstDay = previousWeekLastDay + relativedelta(weekday=MO(-1))
print(previousWeekFirstDay)
print(previousWeekLastDay)
previoustopreviousWeekLastDay1= date_object + relativedelta(weekday=SU(-2))
previoustopreviousWeekFirstDay1= previousWeekLastDay1 + relativedelta(weekday=MO(-1))
print(previoustopreviousWeekFirstDay1)
print(previoustopreviousWeekLastDay1)

Categories

Resources