How to get the year and week before current week? - python

I know current year and current week,for example current year is 2018,current week is 8.
I want to know which year and week is it 10 weeks ago,10 weeks ago is the fiftieth week of 2017.
currentYear=2018
currentWeek=8
How to get it?

In [31]: from datetime import datetime as dt
In [32]: from datetime import timedelta
In [33]: current_date = dt(2018, 2, 20)
In [34]: current_date
Out[34]: datetime.datetime(2018, 2, 20, 0, 0)
In [35]: current_date.strftime('%V') <-- This is how we can get week of year.
Out[35]: '08'
In [36]: current_date - timedelta(weeks=10) <-- How to go back in time.
Out[36]: datetime.datetime(2017, 12, 12, 0, 0)
In [37]: ten_weeks_ago = _
In [38]: ten_weeks_ago.strftime('%V')
Out[38]: '50'

Best way,
Without knowing the date of 8th week of 2018,
Just creating date from week and year
here it is:
import datetime
d = "%s-W%s"%(currentYear,currentWeek)
r = datetime.datetime.strptime(d + '-0', "%Y-W%W-%w")
print(r-datetime.timedelta(weeks=10))
Output:
2017-12-17 00:00:00
Or if want in week format:
print((r-datetime.timedelta(weeks=10)).strftime('%V'))
Output:
50

after importing module import date
import time
from datetime import date
currentYear=datetime.strptime("2018-8-1", "%Y-%W-%w")
representing year and week and need a random weekday day added

Related

How to get date of last friday in each quarter?

I want to find the last friday date in each quater for the given year. For example, the output as follows
last friday in March
last friday in June
last friday in september
last friday in december
How can I find this intelligently based on given year as an input
I'm assuming you don't want the output to be literally
last friday in March
last friday in June
last friday in september
last friday in december
and you just didn't feel like looking up those dates for an example year to include in your question.
Since we know that quarters always end in those months, we can create the last dates of those months. Then, datetime.date.weekday() tells us which day of the week it is. Friday is 4, so we just need to find out how many days we need to go back to achieve this. Then, use datetime.timedelta can subtract that many days, and we should be good to go:
import datetime
def last_fridays_of_quarter(year):
last_days = [datetime.date(year, 3, 31), datetime.date(year, 6, 30), datetime.date(year, 9, 30), datetime.date(year, 12, 31)]
for day in last_days:
days_to_sub = (day.weekday() - 4) % 7
last_friday = day - datetime.timedelta(days=days_to_sub)
print(last_friday)
Testing this for 2022:
>>> last_fridays_of_quarter(2022)
2022-03-25
2022-06-24
2022-09-30
2022-12-30
Here's one way to solve it. You store last days of each quarter in a given year in an array. Then you iterate over said quarter ending dates, and calculate the offset that you would need to subtract in order to get to the previous friday.
from datetime import datetime, timedelta
year = 2022
quarter_ending_dates = [
datetime(year, 3, 31),
datetime(year, 6, 30),
datetime(year, 9, 30),
datetime(year, 12, 31)
]
for ending_date in quarter_ending_dates:
offset = (ending_date.weekday() - 4) % 7
last_friday = ending_date - timedelta(days=offset)
print(last_friday)
try:
import pandas as pd
def fridays(year):
df = pd.date_range(start=str(year), end=str(year+1),
freq='W-FRI').strftime('%m/%d/%Y')\
.to_frame().reset_index(drop = True)
df.columns = ['date']
df.index = pd.to_datetime(df['date']).dt.to_period('Q')
df = df.groupby(df.index).last()
df.index.name = 'quarter'
return df
fridays(2022)
output is:
quarter
date
2022Q1
03/25/2022
2022Q2
06/24/2022
2022Q3
09/30/2022
2022Q4
12/30/2022

How to find all week numbers that are first week of month in a year python

I want to create a event that falls on Sunday of every first week of months.
This is what I am doing for a particular week number which is first week of june to get date:
from datetime import datetime
myDate = "2017 22 0"
# here `2017` is year, `22` is week number and `0` =sunday is week day
datetime.strptime(myDate, "%Y %W %w")
#output...
datetime.datetime(2017, 6, 4, 0, 0)
So I need a list of all week numbers that are first week of month so I can loop on it and get desire dates.
Adding More information
I want a method which return list of week numbers which are first week of month where first week means week has first sunday.
def get_week_number(year=2017, day=0):
#day 0 means sunday
...
...
return [1, 5, 9, 13, 18, 22, ...]
(Edited, because of error in weekday numbering)
>>> import datetime
>>> june1 = datetime.datetime(2017,6,1)
>>> june1
datetime.datetime(2017, 6, 1, 0, 0)
>>> june1_weekday = june1.weekday()
>>> if june1_weekday < 6: # 6 indicates Sunday
first_sunday_in_june = june1 + datetime.timedelta(days=6-june1_weekday)
else:
first_sunday_in_june = june1
>>> print(first_sunday_in_june)
2017-06-04 00:00:00
Assuming you want ISO weeknumbers, you can then use the isocalendar() method. This gives a tuple (year, weeknumber, weekday). This uses the convention that weeks start with Monday, and the first week of the year is the first week with at least four days in the year (or in other words, the week with the first Thursday).
>>> first_sunday_in_june.isocalendar()
(2017, 22, 7)
If you have another convention for first-day-of-the-week or first-week-of-the-year, you will have to brew your own function to get the week number.
Use the above method in a loop over the months, and you can create the desired list with week numbers.
I've done a loop through the months, then got the first Sunday (starting at month's 1st and moving to the next day until a Sunday is found), then got the week-of-year of the date found:
from datetime import datetime
from datetime import date
# dayofweek: Sunday=0, Monday=1 and so on
def get_week_number(year=2017, dayofweek=0):
weeks = []
for month in range(1, 13):
# get first Sunday of month
d = date(year, month, 1)
while(d.weekday() != dayofweek):
d = d.replace(day=d.day + 1)
# isocalendar()[1] is the week-of-year field
weeks.append(d.isocalendar()[1])
return weeks
print(get_week_number(2017, 0))
The result, though, is different from what you expect:
[1, 6, 10, 14, 18, 23, 27, 32, 36, 40, 45, 49]
I also tried with weeks.append(int(d.strftime("%W"))) but it gives the same results - I'm using Python 3.5.2 and a week is defined as:
The ISO year consists of 52 or 53 full weeks, and where a week starts on a Monday and ends on a Sunday. The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday. This is called week number 1, and the ISO year of that Thursday is the same as its Gregorian year.

Datetime from year and week number

I have a year and a week number which I want to convert into a datetime.datetiem object. My (naive?) reading of the documentation hinted that strptime('2016 00', '%Y %W') should do just that. However:
In [2]: from datetime import datetime
In [3]: datetime.strptime('2016 00', '%Y %W')
Out[3]: datetime(2016, 1, 1, 0, 0)
In [4]: datetime.strptime('2016 52', '%Y %W')
Out[4]: datetime(2016, 1, 1, 0, 0)
What am I doing wrong?
So it turns out that the week number isn't enough for strptime to get the date. Add a default day of the week to your string so it will work.
> from datetime import datetime
> myDate = "2016 51"
> datetime.strptime(myDate + ' 0', "%Y %W %w")
> datetime.datetime(2016, 12, 25, 0, 0)
The 0 tells it to pick the Sunday of that week, but you can change that in the range of 0 through 6 for each day.
From the docs (see note 7 at the bottom):
When used with the strptime() method, %U and %W are only used in
calculations when the day of the week and the year are specified.
Thus, as long as you don't specify the weekday, you will effectively get the same result as datetime.strptime('2016', '%Y').

Define starting day in week using hour and not just date

I need to define a "long" week by hour in a day.
The week will start on Tuesday at 12AM and will end on next Tuesday at 6AM.
The next week will do an overlap (again starting from Tuesday at 12AM and so on).
Can this be done with isocalendar or strftime?
I think you need a timedelta, which is part of the standard datetime library:
>>> from datetime import datetime, timedelta
Given a starting date:
>>> start = datetime(year=2015, month=5, day=4, hour=0)
>>> start
datetime.datetime(2015, 5, 4, 0, 0)
You can use timedelta to store the difference between dates:
>>> long_week = timedelta(weeks=1, hours=6)
Add the delta to the start date:
>>> end = start + long_week
>>> end
datetime.datetime(2015, 5, 11, 6, 0)

How to get week start dates and week number of each week in a year considering start day of the week is Monday in python?

How can I get week start dates of each week in a year, considering start day of the week is Monday in python?
This assumes start day is Sunday:
>>>import datetime as datetime
>>>dt = datetime .date(2013,12,30)
>>>dt.isocalendar()[1]
1
However, result shouldn't be 1, because 30-12-2013 is still in 2013.
I don't think behaviour of isocalendar can be changed.
From : http://docs.python.org/2/library/datetime.html#datetime.date.isocalendar
The first week of an ISO year is the first (Gregorian) calendar week of a year containing a Thursday.
But strftime can display week number :
%U "All days in a new year preceding the first Sunday are considered to be in week 0."
%W "All days in a new year preceding the first Monday are considered to be in week 0."
>>> import datetime
>>> dt = datetime.date(2013,12,30)
>>> dt.isocalendar()
(2014, 1, 1)
>>> dt.strftime("%U")
'52'
But to respond to your first question, why don't you just use datetime.timedelta ?
>>> import datetime
>>> dt = datetime.date(2013,12,30)
>>> w = datetime.timedelta(weeks=1)
>>> dt - w
datetime.date(2013, 12, 23)
>>> dt + w
datetime.date(2014, 1, 6)
>>> dt + 10 * w
datetime.date(2014, 3, 10)

Categories

Resources