Python get number of the week by month - python

Any one could help me please, How to get number of week by month in Python?
from datetime import datetime, date, timedelta
Input:
date1 = "2015-07-09"
date2 = "2016-08-20"
Output:
2015-07 : 4
2015-08 : 5
2015-08 : 4
....
2016-08 : 5
How to count number of the week by monthly from date1 to date2?

If you wanted to measure the number of full weeks between two dates, you could accomplish this with datetime.strptime and timedelta like so:
from datetime import datetime, date, timedelta
dateformat = "%Y-%m-%d"
date1 = datetime.strptime("2015-07-09", dateformat)
date2 = datetime.strptime("2016-08-20", dateformat)
weeks = int((date2-date1).days/7)
print weeks
This outputs 58. The divide by 7 causes the number of weeks to be returned. The number of whole weeks is used (rather than partial) because of int which returns only the integer portion. If you wanted to get the number of partial weeks, you could divide by 7.0 instead of 7, and ensure that you remove the int piece.

Try this:
date1 = "2015-07-09"
date2 = "2016-08-20"
d1 = datetime.datetime.strptime(date1, '%Y-%m-%d').date()
d2 = datetime.datetime.strptime(date2, '%Y-%m-%d').date()
diff = d2 -d1
weeks, days = divmod(diff.days, 7)

Related

Counting the number of days in a range by month in Python?

I am trying to count the number of days in a range of dates by month. So let's say a range of dates occurs between 2 months since the beginning and ending dates are in 2 different months. I want the output to show that x amount of days in the range fall in one month and x amount of days fall in the next month.
So far my code only outputs each day in the range from 10 days after veterans day (my start date) to 20 days after veterans day (end date):
import datetime
Veterans = datetime.datetime(2019, 11, 12)
print(Veterans)
number_of_days = 10
ten_days = datetime.timedelta(days=10)
vetplus10 = Veterans + ten_days
date_list = [(vetplus10 + datetime.timedelta(days=day)).isoformat() for day in range(number_of_days)]
print(date_list)
['2019-11-22T00:00:00', '2019-11-23T00:00:00', '2019-11-24T00:00:00',
'2019-11-25T00:00:00', '2019-11-26T00:00:00', '2019-11-27T00:00:00',
'2019-11-28T00:00:00', '2019-11-29T00:00:00', '2019-11-30T00:00:00',
'2019-12-01T00:00:00']
The idea here would be for python to tally up all the days in November (9) and all the days in December (1).
Thank you in advance!
You can try using pandas to create a date range, convert it to a month and get the value counts.
import pandas as pd
pd.date_range(start='2019-11-22', periods=10, freq='D').to_period('M').value_counts()
2019-11 9
2019-12 1
I was able to get similar output without using an additional library:
import datetime
Veterans = datetime.datetime(2019, 11, 12)
print(Veterans)
number_of_days = 10
ten_days = datetime.timedelta(days=10)
vetplus10 = Veterans + ten_days
date_list = [(vetplus10 + datetime.timedelta(days=day)) for day in range(number_of_days)]
day_counts = {}
for day in date_list:
day_counts[f"{day.year}-{day.month}"] = day_counts.get(f"{day.year}-{day.month}", 0) + 1
print(day_counts)
2019-11-12 00:00:00
{'2019-11': 9, '2019-12': 1}
Essentially, I simply iterate over the datetime objects in your original list, and build a dictionary for each year-month that it encounters.

Pandas get date difference between 2 ISO date

I have 2 date strings: 2020-02-12T16:02:51Z and 2017-03-08T18:16:02-05:00, and I'd like to get the difference in days that includes partial day difference (for example, a difference of 1 day 12 hours 00 minutes 00 seconds will be 1.5 days).
Here is what I have:
import pandas as pd
date1 = pd.to_datetime("2020-02-12T16:02:51Z", utc=True)
date2 = pd.to_datetime("2017-03-08T18:16:02-05:00", utc=True)
diff = date1 - date2
diff.days
>>> 1070
I expect it should be 1070.<some decimal digits>. Because diff is Timedelta('1070 days 16:46:49')
What did I do wrong? I am using Python 3.8.1 and pandas 1.0.1
Timedelta.days represents the number of days in the delta. So, in your case 1070.
However, you have different options to get the results in fractional form.
>>> diff = date1 - date2
>>> diff.days + diff.seconds/86400
1070.6991782407408
>>> diff.total_seconds()/86400
1070.6991782407408
You are not doing anything wrong. pandas.Timedelta.days returns full days in the timedelta object. You can find fractional days with using diff.value (which returns nanoseconds), such as:
import pandas as pd
date1 = pd.to_datetime("2020-02-12T16:02:51Z", utc=True)
date2 = pd.to_datetime("2017-03-08T18:16:02-05:00", utc=True)
diff = date1 - date2
# nano seconds to days
diff.value / 8.64e+13
>>> 1070.6991782407408

Reverse of datetime.weekday()?

d : Datetime object
Given a date d and a day of the week x in the range of 0–6, return the date of x within the same week as d.
I can think of some ways to do this, but they all seem rather inefficient. Is there a pythonic way?
Example
Input: datetime(2020,2,4,18,0,55,00000), 6
Output: date(2020,2,7)
Input: datetime(2020,2,4,18,0,55,00000), 0
Output date(2020,2,3)
This approach gets the first day in the week and goes from there to find the date requested by the weekday integer:
import datetime as dt
def weekday_in_week(d,weekday=None):
if not weekday:
return None
week_start = d - dt.timedelta(days=d.weekday())
return week_start + dt.timedelta(days=weekday)
Example usage:
In [27]: weekday_in_week(dt.date.today(),6)
Out[27]: datetime.date(2020, 2, 9)
Remember that the weekdays are as such: 0 is Monday, 6 is Sunday.

How to group dates based on day?

To simplify my problem, I have dates like these:
2019-10-05 # Day 1 => starting point
2019-10-07 # Day 3
2019-10-07 # Day 3
2019-10-09 # Day 5
2019-10-10 # Day 6
2019-10-10 # Day 6
result should be: {1: ['2019-10-05'], 3: ['2019-10-07', '2019-10-07'], and so on...}
I feel that there is a module in Python (probably Collections?) that can solve for this but I don't exactly know what terminology should I use that is applicable to this problem other than grouping dates in day.
with some amount of conversion between strings and dates (strptime does the heavy lifting)... you could do this:
from datetime import datetime
from collections import defaultdict
# the date format (for strptime)
fmt = "%Y-%m-%d"
startdate = datetime.strptime('2019-10-05', fmt).date()
# the dates as strings
date_str_list = [
"2019-10-07", # Day 3
"2019-10-07", # Day 3
"2019-10-09", # Day 5
"2019-10-10", # Day 6
"2019-10-10" # Day 6
]
# converting to date objects
date_list = [datetime.strptime(date_str, fmt).date() for date_str in date_str_list]
res = defaultdict(list)
for date in date_list:
res[(date - startdate).days + 1].append(str(date))
print(res)
# defaultdict(<class 'list'>, {3: ['2019-10-07', '2019-10-07'],
# 5: ['2019-10-09'], 6: ['2019-10-10', '2019-10-10']})
where i use defaultdict as the container.
the difference of two date object is a timedelta object; .days gives the number of days thereof.

Week Number for Actual Calendar Python

Can someone tell me how to get a week number in Python for actual calendar.
Ex: 2016-01-01 to 2016-01-07 = week 1
2016-01-08 to 2016-01-14 = week 2
I tried 2 ways but none of them are working
Using isocalendar()
But that does not work for year end and year start week. For ex:
datetime.date(2016,01,01).isocalendar()[1]
# should be: 1
# got 53
is the following:
dt = date(2016,01,02)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 00
dt = date(2016,01,03)
d = strftime("%U", time.strptime(str(dt),"%Y-%m-%d"))
print d
# 01
Both the ways do not satisfy my requirement. Is there any other library I can use to get the week number in Actual Calendar ?
Are you talking about actual number of 7 day periods rather than which week number you're in? Keep in mind in 2016, Jan 3rd is the first day of the second week.
If you're looking at which 7 day period, you should simply count days since the beginning of the year and floor div by 7
dt = datetime.datetime(year=2016, month=1, day=2)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
The 29th should be the first day of week 5. Let's try it.
dt = datetime.datetime(year=2016, month=1, day=29)
days = dt - datetime.datetime(year=dt.year, month=1, day=1).days
weeks = days // 7 + 1
# 5

Categories

Resources