Calculate years + months + days between 2 dates? [duplicate] - python

This question already has answers here:
calculate the difference between two datetime.date() dates in years and months
(3 answers)
Closed 4 years ago.
I have 2 person's birth information, I want to do some analysis on them.
Like, the difference between their age, seconds, years+months+days.
I tried this:
from datetime import date
a = date(1991, 07, 20)
b = date(1999, 06, 06)
print((a-b).days)
-2878
this gives me 2878 days, but i want to calculate years + months + days
i tried to divide 2878/365, but i want the exact calculations
How can i approach this?
Expected Output:
7 years x months x days

Use datetime and dateutil:
from datetime import datetime
from dateutil import relativedelta
date1 = datetime(1991, 7, 20)
date2 = datetime(1999, 6, 6)
diff = relativedelta.relativedelta(date2, date1)
years = diff.years
months = diff.months
days = diff.days
print('{} years {} months {} days'.format(years, months, days))
# 7 years 10 months 17 days

For strict differences, i.e. differences between years, months and days, you can use the attributes of timedelta objects.
from datetime import date
a = date(1991, 7, 20)
b = date(1999, 6, 6)
months = a.month - b.month
years = a.year - b.year
days = a.day - b.day
print('{0} years, {1} months, {2} days'.format(years, months, days))
-8 years, 1 months, 14 days
For time-aware differences, you can use 3rd party dateutil as per #Austin's solution.

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.

Python elegant way of finding the last weekday [duplicate]

This question already has answers here:
Previous weekday in Python
(4 answers)
Closed 1 year ago.
I need to find the last weekday (without considering holidays). Is there any more elegant/robust way of implementing this than the one I'm currently using?
from datetime import date
b = date.today() - timedelta(days=1)
while b.weekday()>=5:
b = b - timedelta(days=1)
Something like this might work (untested):
from datetime import date, timedelta
b = date.today() - timedelta(days=1)
current_day = b.weekday() # 0 for Monday, 6 for Sunday
# go back 1 day for Sat, 2 days for Sun, 0 for other days
days_to_go_back = max(current_day - 4, 0)
b -= timedelta(days=days_to_go_back)

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

How to get month interval using "datetime" in python? [duplicate]

This question already has answers here:
How to get the last day of the month?
(44 answers)
Closed 8 years ago.
As every month have different days in it, so i can't apply timedelta=30.
I want to get three variables
month_start,
month_end ,
month_days = month_end - month_start
Which will be correspond to start date of month and end date of month. and their interval will be number of days in the month.
for instance , for march : month_days = 31, april : month_days = 30
Use calendar module to get days from months
>>> import datetime
>>> import calendar
>>> now = datetime.datetime.now()
>>> print calendar.monthrange(now.year, now.month)[1]
31
For 2015 Feb month
>>> calendar.monthrange(2015, 2)
(6, 28)
https://docs.python.org/2/library/calendar.html

Calculate number of days for last 6months from today in python

In python how to find the total number of days for the last 6 months ?
For example today is 7 November(7 days in this month), and in october there are 31 days and so on until the last 6 months, and now i need to find the total for all the days in a month(until the last 6 months) like
7(Nov) + 31(Oct) + 30(Sep) +... until the last 6 months from now
with dateutil:
>>> from dateutil.relativedelta import relativedelta
>>> import datetime
>>> delta = relativedelta(months=6)
>>> six_month_away = datetime.date.today() - delta
>>> abs((six_month_away - datetime.date.today()).days)
184

Categories

Resources