Python How to calculate number of days between 2 dates? [duplicate] - python

This question already has answers here:
How to calculate number of days between two given dates
(15 answers)
Closed 8 years ago.
I'm having trouble doing this in a clean and simple way in python.
What I'd like to do is having a piece of code that calculates the number of days passed between 2 dates.
For example today being the 22nd of december and i want to know how many days i have before the 15th of febuary. There are 55 days difference
(i took this example because it englobes 2 different years an multiple months)
What i made was very messy and dosen't work half the time so i'm kind of embarrassed to show it.
Any help is appreciated.
Thanks in advance

Simpler implementation:
import datetime
d1 = datetime.datetime(2013,12,22)
d2 = datetime.datetime(2014,2,15)
(d2-d1).days

just create an instance of both the dates and substract them - you'll get timedelta object with a given info.
>>> from datetime import date
>>> by = date(2013, 12, 22)
>>> since = date(2014, 2, 15)
>>> res = since - by
>>> res.days
55
some examples with a variables
>>> variables_tuple = (2013, 12, 22)
>>> by = date(*variables_tuple)
>>> by.year
2013
>>> until_year = 2014
>>> until = date(until_year, 2, 15)

Related

Django how to get days count of month in specific year [duplicate]

This question already has answers here:
How to get the last day of the month?
(44 answers)
Closed 9 years ago.
I need to calculate the number of days for a given month in python. If a user inputs Feb 2011 the program should be able to tell me that Feb 2011 has 28 days. Could anyone tell me which library I should use to determine the length of a given month?
You should use calendar.monthrange:
>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)
Just to be clear, monthrange supports leap years as well:
>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)
As #mikhail-pyrev mentions in a comment:
First number is the weekday of the first day of the month, the second number is the number of days in said month.
Alternative solution:
>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29
Just for the sake of academic interest, I did it this way...
(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

Calculating how many days are in a month [duplicate]

This question already has answers here:
How to get the last day of the month?
(44 answers)
Closed 9 years ago.
I need to calculate the number of days for a given month in python. If a user inputs Feb 2011 the program should be able to tell me that Feb 2011 has 28 days. Could anyone tell me which library I should use to determine the length of a given month?
You should use calendar.monthrange:
>>> from calendar import monthrange
>>> monthrange(2011, 2)
(1, 28)
Just to be clear, monthrange supports leap years as well:
>>> from calendar import monthrange
>>> monthrange(2012, 2)
(2, 29)
As #mikhail-pyrev mentions in a comment:
First number is the weekday of the first day of the month, the second number is the number of days in said month.
Alternative solution:
>>> from datetime import date
>>> (date(2012, 3, 1) - date(2012, 2, 1)).days
29
Just for the sake of academic interest, I did it this way...
(dt.replace(month = dt.month % 12 +1, day = 1)-timedelta(days=1)).day

Calculating the date a fixed number of days from given date [duplicate]

This question already has answers here:
Days between two dates? [duplicate]
(4 answers)
Closed 5 years ago.
I need to design a code that will automatically generate the date X number of days from current date.
For that, I currently have a function that returns an epoch timestamp, which I then add the fixed number of days in seconds. However, I am currently stuck there and do not know how to convert the epoch timestamp into a Gregorian calendar date format (DD/MM/YYYY HH:MM). Displaying time is optional, can be rounded to the nearest day.
A way to do this without using an epoch timestamp and directly getting the current date in a readable format, printing it, and adding X days to it before generating the second date, is also fine, but I have no idea how that would work.
Any help/input would be much appreciated. Thanks in advance.
You can use timedelta.
import datetime as dt
x = 5 # Days offset.
now = dt.datetime.now()
>>> now + dt.timedelta(days=x)
datetime.datetime(2017, 12, 2, 21, 10, 19, 290884)
Or just using days:
today = dt.date.today()
>>> today + dt.timedelta(days=x)
datetime.date(2017, 12, 2)
Easy enough to convert back to a string using strftime:
>>> (today + dt.timedelta(days=x)).strftime('%Y-%m-%d')
'2017-12-02'
import datetime
x = 5
'''
Date_Time = datetime.datetime.now()#It wil give Date & time both
Time = datetime.datetime.now().time()#It will give Time Only
'''
Date = datetime.datetime.now().date()#It will give date only
print(Date + datetime.timedelta(days=x))#It will add days to current date
Output:
2017-12-03

Get a date based on week number (python) [duplicate]

This question already has answers here:
What's the best way to find the inverse of datetime.isocalendar()?
(8 answers)
Closed 8 years ago.
I'm writing a script where the user needs to input a week number and a procedure will be ran based on that. However, I ran into a small issue, I know I can get week numbers via something like this:
>>> a=datetime.datetime.now()
>>> a
datetime.datetime(2015, 1, 22, 15, 51, 57, 820058)
>>> a.isocalendar()[1]
4
But I can't find how to do it backwards. Also, the date I require has to be Sunday of that week at 6:00am. Once I have that datetime element I can just do
begin_date = datetime.datetime.strptime(a, "%Y-%m-%d %H:%M:%S")
To get the format I want. I'm still missing the step to get the date. Any thoughts?
We create an initial datetime of for 2015 (2014-12-28 6:00:00 --1st sunday of 1st week), and a timedelta object of 7 days:
w0 = datetime.datetime(2014,12,28,6)
d7 = datetime.timedelta(7)
Then you can simply add multiples of the timedelta object to the initial date like so (n would be your week number):
w0+(d7*n)
>>> now = datetime.datetime.now()
>>> start = datetime.datetime(2015, 1,1)
>>> (now - start).days // 7
3

Date 6 months into the future

I am using the datetime Python module in django. I am looking to calculate the date if the expiry date is less than or equal to 6 months from the current date.
The reason I want to generate a date 6 months from the current date is to set an alert that will highlight the field/column in which that event occurs. I dont know if my question is clear. I have been reading about timedelta function but cant really get my head round it. I am trying to write an if statement to statisfy this condition. Anyone able to help me please? Am a newbie to django and python.
There are two approaches, one only slightly inaccurate, one inaccurate in a different way:
Add a datetime.timedelta() of 365.25 / 2 days (average year length divided by two):
import datetime
sixmonths = datetime.datetime.now() + datetime.timedelta(days=365.25/2)
This method will give you a datetime stamp 6 months into the future, where we define 6 monhs as exactly half a year (on average).
Use the external dateutil library, it has a excellent relativedelta class that will add 6 months based on calendar calculations to your current date:
import datetime
from dateutil.relativedelat import relativedelta
sixmonths = datetime.datetime.now() + relativedelta(months=6)
This method will give you a datetime stamp 6 months into the future, where the month component of the date has been forwarded by 6, and it'll take into account month boundaries, making sure not to cross them. August 30th plus 6 months becomes February 28th or 29th (leap years permitting), for example.
A demonstration could be helpful. In my timezone, at the time of posting, this translates to:
>>> import datetime
>>> from dateutil.relativedelta import relativedelta
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2013, 2, 18, 12, 16, 0, 547567)
>>> now + datetime.timedelta(days=365.25/2)
datetime.datetime(2013, 8, 20, 3, 16, 0, 547567)
>>> now + relativedelta(months=6)
datetime.datetime(2013, 8, 18, 12, 16, 0, 547567)
So there is a 1 day and 15 hour difference between the two methods.
The same methods work fine with datetime.date objects too:
>>> today = datetime.date.today()
>>> today
datetime.date(2013, 2, 18)
>>> today + datetime.timedelta(days=365.25/2)
datetime.date(2013, 8, 19)
>>> today + relativedelta(months=6)
datetime.date(2013, 8, 18)
The half-year timedelta becomes a teensy less accurate when applied to dates only (the 5/8th day component of the delta is ignored now).
If by "6 months" you mean 180 days, you can use:
import datetime
d = datetime.date.today()
d + datetime.timedelta(6 * 30)
Alternatively if you, mean actual 6 months by calendar you'll have to lookup the calendar module and do some lookups on each month. For example:
import datetime
import calendar
def add_6_months(a_date):
month = a_date.month - 1 + 6
year = a_date.year + month / 12
month = month % 12 + 1
day = min(a_date.day,calendar.monthrange(year, month)[1])
return datetime.date(year, month, day)
I would give Delorean a look a serious look. It is built on top of dateutil and pytz to do what you asked would simply be the following.
>>> d = Delorean()
>>> d
Delorean(datetime=2013-02-21 06:00:21.195025+00:00, timezone=UTC)
>>> d.next_month(6)
Delorean(datetime=2013-08-21 06:00:21.195025+00:00, timezone=UTC)
It takes into account all the dateutil calculations as well as provide and interface for timezone shifts. to get the needed datetime simple .datetime on the Delorean object.
this might work for you in case you want to get an specfic date back:
from calendar import datetime
datetime.date(2019,1,1).strftime("%a %d")
#The arguments here are: year, month, day and the method is there to return a formated kind of date - in this case - day of the week and day of the month.
The outcome would be:
Tue 01
Hope it helps!

Categories

Resources