how to get week number on python? [duplicate] - python

This question already has answers here:
Python: Number of the Week in a Month
(9 answers)
Closed 7 years ago.
I want to get week number like picture below
If I insert 20150502, It should print "week 1".
If I insert 20150504, It should print "week 2".
If I insert 20150522, It should print "week 4".
How to get week number?

Here's a quick attempt, as with all date/time code there are probably a lot of edge cases that can cause strange results.
# dateutil's parser is very good for converting from string to date
from dateutil.parser import parse
date_strs = ['20150502', '20150504', '20150522']
for date_str in date_strs:
d = parse(date_str)
month_start = datetime.datetime(d.year, d.month, 1)
week = d.isocalendar()[1] - month_start.isocalendar()[1] + 1
print(date_str + ':', week)
Output:
20150502: 1
20150504: 2
20150522: 4

Related

python get the previous week number as YYYYWW [duplicate]

This question already has answers here:
How can I get the previous week in Python?
(1 answer)
How to get Year-Week format in ISO calendar format?
(2 answers)
Closed last month.
I have a year and week number in an integer format, and I would like to get the previous week number.
I currently have this code:
# get previous week number (as an integer)
weeknumber = 202302
year = weeknumber//100
week = weeknumber-year*100
day = 1
prev_weeknumber = int(''.join(map(str,((datetime.fromisocalendar(year,week,day))- timedelta(days = 7)).isocalendar()[0:2])))
But it provides the following output
prev_weeknumber = 20231
While I need it to have this output
prev_weeknumber = 202301

How can I have the exact date for a certain week of the year? [duplicate]

This question already has answers here:
Pandas: How to create a datetime object from Week and Year?
(4 answers)
Closed 4 months ago.
I have the following data:
week = [202001, 202002, 202003, ..., 202052]
Where the composition of the variable is [year - 4 digits] + [week - 2 digits] (so, the first row means it's the first week of 2020, and so on).
I want to transform this, to a date-time variable [YYYY - MM - DD]. I'm not sure what day could fit in this format :( maybe the first saturday of every week.
week_date = [2020-01-04, 2020-01-11, 2020-01-18, ...]
It seems like a simple sequence, neverthless I have some missings values on the data, so my n < number of weeks of 2020.
The main purpose of this conversion is that I can have a fit model to train in prophet. I also think I need no missing values when incorporating the data into prophet, so maybe the answer could be also adding 0 to my time series?
Any ideas? Thanks
Try:
l = [202001, 202002, 202003, 202052]
out [datetime.datetime.fromisocalendar(int(x[:4]), int(x[4:]), 6).strftime("%Y-%m-%d") for x in map(str,l)]
print(out)
outputs:
['2020-01-04', '2020-01-11', '2020-01-18', '2020-12-26']
Here I used 6 as the week day but chose as you want
This makes a datetime object from the first and last part of each number after mapping them to a string, then outputs a string back with strftime and the right format.

How to calculate number of weeks between two ISO dates [duplicate]

This question already has answers here:
What's the best way to find the inverse of datetime.isocalendar()?
(8 answers)
Closed 2 years ago.
I am reading excel files line by line where I have in one column ISO year_week_start : 2020_53 and in second ISO year_week_end : 2021_01
I am looking how to get distance between these two strings
2021_01 - 2020_53 => 1
2020_40 - 2020_30 => 10
Is this what you are looking for?
from datetime import date
def convert(value):
(year, week) = [int(x) for x in value.split('_')]
result = date.fromisocalendar(year, week, 1)
return result
def distance(date1, date2):
date1 = convert(date1)
date2 = convert(date2)
diff = date1 - date2
weeks = diff.days / 7
return weeks
print(distance('2021_01', '2020_53'))
print(distance('2020_40', '2020_30'))
print(distance('2021_01', '1991_01'))
Output
1.0
10.0
1566.0

Finding the day x years,months from a given time (Python) [duplicate]

This question already has answers here:
python getting weekday from an input date
(2 answers)
Closed 9 years ago.
Have a maths question here which I know to solve using only pen and paper. Takes a while with that approach, mind you. Does anybody know to do this using Python? I've done similar questions involving "dates" but none involving "days". Any of you folk able to figure this one out?
The date on 25/11/1998 is a Wednesday. What is the day on 29/08/2030?
Can anyone at least suggest an algorithm?
Cheers
Use the wonderful datetime module:
>>> import datetime
>>> mydate = datetime.datetime.strptime('29/08/2030', '%d/%M/%Y')
>>> print mydate.strftime('%A')
Tuesday
The algorithm/math is quite simple: There are always 7 days a week. Just calculate how many days between the two days, add it to the weekday of the given day then mod the sum by 7.
<!-- language: python -->
> from datetime import datetime
> given_day = datetime(1998,11,25)
> cal_day = datetime(2030,8,29)
> print cal_day.weekday()
3
> print (given_day.weekday() + (cal_day-given_day).days) % 7
3

get year from string '07-JUL-50' [duplicate]

This question already has answers here:
2 digit years using strptime() is not able to parse birthdays very well
(3 answers)
Closed 9 years ago.
I have a birth date field like:
date = '07-JUL-50'
and when I wanna get the year I got this:
my_date = datetime.datetime.strptime(date, "%d-%b-%y")
>>> my_date.year
2050
Is there an elegant way of get '1950'??
Thx
Documentation says that:
When 2-digit years are accepted, they are converted according to the
POSIX or X/Open standard: values 69-99 are mapped to 1969-1999, and
values 0–68 are mapped to 2000–2068.
That's why you are seeing 2050.
If you want 1950 instead, it depends on what are allowed dates in your particular scenario. E.g. if date values can be only dates in the past, you can do something like this:
import datetime
def get_year(date):
my_date = datetime.datetime.strptime(date, "%d-%b-%y")
now = datetime.datetime.now()
if my_date > now:
my_date = my_date.replace(year=my_date.year - 100)
return my_date.year
print get_year('07-JUL-50') # prints 1950
print get_year('07-JUL-13') # prints 2013
print get_year('07-JUL-14') # prints 1914
Hope that helps.

Categories