Python: Give Start and End of Week Data from a Given Date

get the start and end timestamp of the current week in python

You can use datetime.replace():

from datetime import date, datetime, timedelta
today = datetime.now() # or .today()
start = (today - timedelta(days=today.weekday())).replace(hour=0, minute=0, second=0, microsecond=0)
end = (start + timedelta(days=4)).replace(hour=23, minute=59, second=0, microsecond=0)
print("Today: " + str(today))
print("Start: " + str(start))
print("End: " + str(end))

output

Today: 2021-07-08 22:56:19.277242
Start: 2021-07-05 00:00:00
End: 2021-07-09 23:59:00

Python: Calculate week start and week end from daily data in pandas dataframe?

The first step would be to create a new column for the start date and end date for the date of each row. This can be done by using offsets.Week:

import pandas as pd    

df['start'] = df['dates'] - pd.offsets.Week(weekday=6)
df['end'] = df['start'] + pd.offsets.Week(weekday=5)

From there you can use groupby to group by the start, end, product and country columns and use the mean aggregation method for the value column:

df.groupby(['start','end','product','country']).agg({'value': 'mean'}).reset_index()

Given number of days and date then find the start or end date in python

This might just work:

from datetime import date, timedelta

day1 = date(2021, 9, 9)
difference = timedelta(days=10)
day2 = day1 - difference #Your answer
print(day2)

Getting the date of the first day of the week

To get the beginning date of the week from Sunday:

datetime.today() - datetime.timedelta(days=datetime.today().isoweekday() % 7)

how get the last week as start date and end date based on date in current week in scrapy

You can use datetime.timedelta for that.

It has an optional weeks argument, which you can set to -1 so it will subtract seven days from the date.

You will also have to subract the current date's weekday (and another one, to even the day since the Monday is 0).

import datetime

def previous_week_range(date):
start_date = date + datetime.timedelta(-date.weekday(), weeks=-1)
end_date = date + datetime.timedelta(-date.weekday() - 1)
return start_date, end_date

previous_week_range(datetime.date(2015, 2, 9)) # 2015-02-02, 2015-02-08
previous_week_range(datetime.date(2015, 2, 13)) # 2015-02-02, 2015-02-08
previous_week_range(datetime.date(2015, 2, 16)) # 2015-02-09, 2015-02-15


Related Topics



Leave a reply



Submit