Check if date is between two dates without year included - python

I have a datetime date in the format yyyy-mm-dd and I want to check if the date entered falls between for example May 15th and May 25th without including any year value.
tripDate_str = str(input("Please enter the trip start date in the following format: YYYY-MM-DD "))
import datetime
tripDate = datetime.datetime.strptime(tripDate_str, "%Y-%m-%d")

Well I guess the simplest approach is to use the month and day date class attributes
import datetime
tripDate = datetime.datetime.strptime('2022-05-15', "%Y-%m-%d")
start = datetime.datetime.strptime('2022-05-10', "%Y-%m-%d")
end = datetime.datetime.strptime('2022-05-20', "%Y-%m-%d")
if tripDate.month >= start.month and tripDate.month <= end.month and tripDate.day >= start.day and tripDate.day <= end.day:
print('Date in range')
else:
print('Date not in range')

There are many options to get the day of the year from a date. Use a search engine with keywords python day of year to find out which or just look here at stackoverflow ("Convert Year/Month/Day to Day of Year in Python"). The code below is using for this purpose dateObject.timetuple().tm_yday:
tripDate_str = str(input("Please enter the trip start date in the following format: YYYY-MM-DD "))
# tripDate_str = "2022-05-18"
## Finding day of year
from datetime import date
tripDate = date(*map(int, tripDate_str.split('-')))
tripDate_dayOfYear = tripDate.timetuple().tm_yday
print("Day of year: ", tripDate_dayOfYear, type(tripDate_dayOfYear))
dateRangeBeg_dayOfYear = date(tripDate.year, 5, 15).timetuple().tm_yday
dateRangeEnd_dayOfYear = date(tripDate.year, 5, 25).timetuple().tm_yday
if dateRangeBeg_dayOfYear <= tripDate_dayOfYear <= dateRangeEnd_dayOfYear:
print("tripDate falls into range", dateRangeBeg_dayOfYear, dateRangeEnd_dayOfYear)
else:
print("tripDate is outside range", dateRangeBeg_dayOfYear, dateRangeEnd_dayOfYear)
To avoid a problem with leap years tripDate.year is used in setting the values of dateRangeBeg_dayOfYear and dateRangeEnd_dayOfYear.

Related

could anyone identify the days python?

ask the user enter the date in the format YYYY-MM-DD
1.what age of user in days;
2.what day of week (in German language) was the birth.
import datetime
b = int(input('Enter your birthdate: '))
bb = datetime(b, '%Y-%m-%d')
a = datetime.date.today()
c = a-bb
print(c)
from datetime import datetime
d = input("Enter the date of birth: ")
print(d.strftime('%A'))
Your problem is trying to convert an input that's probably in YYYY-MM-DD format, into an int. This will not work in Python. Simply leave as a string and convert to a date.
Use setlocale to choose German for output.
from datetime import datetime
from datetime import date
# set language output to German
import locale
locale.setlocale(locale.LC_TIME, 'de_DE.UTF-8')
# convert a str to a date, subtract with current date to get # of days
date_time_str = input('Enter your birthdate: ')
bday = datetime.strptime(date_time_str, '%Y-%m-%d').date()
today = date.today()
print(today - bday)
# reuse the "bday" variable defined above, get day of week (in German)
print(bday.strftime('%A'))
Output:
730 days, 0:00:00
Mittwoch

Why is my program outputting the wrong number of days?

So I am writing a program to work out the number of days you have been alive after imputting your birthday. There is a problem as i am getting the wrong number of days but can figure out why. i inputted my birthday as 04/04/19 and i got 730625 days which is clearly wrong.
import datetime #imports module
year = int(input("What year were you born in"))
month = int(input("What month where you born in (number)"))
date = int(input("What date is your birthday? "))
birthdate = datetime.date(date, month, year) #converts to dd/mm/yy
today = datetime.date.today() #todays date
daysAlive = (today - birthdate).days #calculates how many days since birth
print("You have been alive for {} days.".format(daysAlive)) #outputs result
I initially got the same error as you but then I checked my code and managed to fix my mistake.
So your DOB is 04/04/19, when you input that into datetime.date() and it looks at the value for year which is 19, it will treat that as 0019. As in 19 AD, not 2019. You should make sure that you input the full year.
Also like SimonN said, the parameters for datetime.date() are year, month, day, not the other way around.
You have the parameters the wrong way round in datetime.date they should be (year,month,day)
datetime takes arguments as (year, month, date). Note that you cannot enter year like 09 for 2009. Datetime will count it as 0009-MM-DD. You have to enter complete year in the input as 2009
...
birthdate = datetime.date(year, month, date)
...
So, with your input, the output for me is (It may differ with your timezone):
You have been alive for 170 days.
class datetime.date(year, month, day)
should be in the format yy/mm/dd.
Try this code for Python 3.6 or higher,
because of f-stings:
import datetime
year = int(input("What year were you born in: "))
month = int(input("What month were you born in (number): "))
day = int(input("What day were you born in: "))
birth_date = datetime.date(year, month, day) # converts to yy/mm/dd
today = datetime.date.today() # todays date
days_alive = (today - birth_date).days # calculates how many days since birth
print(f"You are {days_alive} days old.") # outputs result
Check the answer using other sources.

How to subtract a date object from another in Python

I want to find how many days there are between two days. The next step is to find out how many hours there are between two days, but that's for later. I created a date object with today's date, and another date object with user inputs, then subtract the smaller date from the larger date. I think this is where I'm going wrong because it does not make sense to subtract a date from another date when both are naive, but it would make sense to subtract a datetime from another datetime (aware)?
I've verified the types of the objects using print(type(var)). Both created objects are of type date, and the result of subtracting is a timedelta object, as expected. Subtracting the date objects gives me the wrong number of days (400 something) when it should be 350 in my case.
from datetime import date, timedelta, datetime
days = list(range(1, 32))
months = list(range(1, 13))
today = date.today()
def inputInteger(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Please enter an integer.")
continue
else:
return userInput
break
def inputMonth(message):
while True:
message = inputInteger(message)
if message in months:
return message
break
else:
print("Please pick a value from 1-12")
def inputDay(message):
while True:
message = inputInteger(message)
if int(message) in days:
return message
break
else:
print("Please pick a value from 1-31")
year = int(inputInteger('Enter a year'))
month = int(inputMonth('Enter a month (1-12)'))
day = int(inputDay('Enter a day (1-31)'))
# 2. add exception handling: leap years, leap seconds?, etc.
significantDate = date(year, month, day)
print("significant date:", significantDate, "of type", type(significantDate))
print("today:", today, "of type", type(today))
# 2. Tell me how many days are left until a certain date
if today > significantDate:
delta = today - significantDate
print("Days left:", delta.days)
else:
print("entered less than")
delta = significantDate - today
print("Days left:", delta.days)
```
from datetime import datetime
year = int(inputInteger('Enter a year'))
month = int(inputMonth('Enter a month (1-12)'))
day = int(inputDay('Enter a day (1-31)'))
significantDate =datetime.strptime(str(year) +str(month) + str(day), '%Y%m%d')
today = datetime.now()
print(today)
dt = today - significantDate
print(dt.days)

How to increment date (month and year) and set the day to default based on specific conditions?

My Date should always fall on 8th or 22nd that comes off the input date.
For Example:
If the input date is 20190415 then the output date should be 20190422 as that's the nearest date and if input date is 20190424 then the output date should be 20190508.
Example1:
input_date = 20190415
Expected output_date = 20190422
Example2:
input_date = 20190424
Expected output_date = 20190508
Example3:
input_date = 20190506
Expected output_date = 20190508
Example4:
input_date = 20191223
Expected output_date = 20200108
How do we achieve this using Python?
You can check if the day is greater than 22, and if so you set it to the 8th of the next month. If it's between 8 and 22 you set it to 22 of the same month and if it's below the 8th you set it to the 8th of the month. There's probably more elegant ways to do it using date math, but this will work for your scenario.
Use the datetime module to find out what the "next month" is. One way to do it is to add a timedelta of 1 month to the first of the current month, and then change the date on that datetime object to the 8th. Here's a quick example of how that might look like:
from datetime import date, timedelta
input_date = date(2019, 12, 23)
if input_date.day > 22:
output_date = date(input_date.year, input_date.month) + timedelta(days=31)
output_date = output_date.replace(day = 8)
You can read a lot more about the details of how the datetime module works on the official documentation. It's kind of a long read, but I actually have that page bookmarked because I always have to go back and reference how to actually use the module :)
Considering the input as string, next date can be calculated using timedelta, check out the below code:
if 8<datetime.strptime(input_date, "%Y%m%d").day < 22:
delta = 22 - datetime.strptime(input_date, "%Y%m%d").day
print((datetime.strptime(input_date, "%Y%m%d") +
timedelta(days=delta)).strftime("%Y%m%d"))
elif datetime.strptime(str(input_date), "%Y%m%d").day < 8:
delta = 8 - datetime.strptime(input_date, "%Y%m%d").day
print((datetime.strptime(input_date, "%Y%m%d") +
timedelta(days=delta)).strftime("%Y%m%d"))
else:
delta = (datetime.strptime(input_date, "%Y%m%d")+ relativedelta(months=+1)).day -8
print((datetime.strptime(input_date, "%Y%m%d") + relativedelta(months=+1) -
timedelta(days=delta)).strftime("%Y%m%d") )

Calculating remaining days between 2 dates inputed by user

I am trying to calculate the number of days between two dates where the user is inputing the dates but cannot find how to do it. I currently have this code:
from datetime import date
startdate = date(input("When do you intend to start?"))
enddate = date(input("When is your deadline?"))
numstudydays = enddate - startdate
print (numstudydays)
Thank you
In python, input() method accepts the input as a string variable. You can then typecast it into an integer using int() method. But you cannot typecast an entire tuple. i.e (year, month, day) in your case.
You can do it by getting all the values one by one.
from datetime import date
print("Enter intended start date details: ")
year = int(input('Year: '))
month = int(input('Month: '))
day = int(input('Day: '))
startdate = date(year, month, day)
print("Enter intended enddate details: ")
year = int(input('Year: '))
month = int(input('Month: '))
day = int(input('Day: '))
enddate = date(year, month, day)
numstudydays = enddate - startdate
print (numstudydays)
Hope that helps.
You are making an incorrect use of the datetime constructor. I revised your solution to handle user input in a simple and manageable way. A basic data validation is performed by the datetime.strptime factory method but there could be more (like checking, for example, that the end date always comes after the start date):
from datetime import datetime, date
start, end = None, None
while start is None:
rawinput = input("When do you intend to start? ")
try:
# %Y stands for a fully specified year, such as 2017, 1994, etc.
# %m for the integer representation of a month, e.g. 01, 06, 12
# and %d for the day of the month
# see https://docs.python.org/3/library/time.html#time.strftime for more
start = datetime.strptime(rawinput, "%Y %m %d")
except ValueError:
print("Input must be \"<year number> <month number> <day number>\"")
while end is None:
rawinput = input("When is your deadline? ")
try:
end = datetime.strptime(rawinput, "%Y %m %d")
except ValueError:
print("Input must be \"<year number> <month number> <day number>\"")
diff = end - start
print("You have %d days of time" % diff.days)
I did more than a couple of tests, and this is what resulted:
None#vacuum:~$ python3.6 ./test.py
When do you intend to start? 2017 01 32
Input must be "<year number> <month number> <day number>"
When do you intend to start? 2017 01 31
When is your deadline? 2017 02 30
Input must be "<year number> <month number> <day number>"
When is your deadline? 2017 02 28
You have 28 days of time
I think your biggest issue is how you retrieve the date.
date() function requires three integers, e.g. date(2017,10,10)
When you use input() you get a string:
input() #returns a string
You would also need to solve this by splitting the input somehow:
e.g.
"2017-10-12".split("-") # returns ["2017","10","12"]
[int(i) for i in "2017-10-12".split("-")] # returns [2017,10,12]
That means if you do this, you get a date:
date(*[int(i) for i in input("When is your deadline?").split("-")])
But what you really want in this case is to use strptime. Strptime() converts a string to a datetime by defining how it looks:
from datetime import datetime
datetime.strptime("20171012","%Y%m%d").date() # returns: datetime.date(2017, 10, 12)
Example of full script
from datetime import datetime
startdate_str = input("When do you intend to start? e.g.(2017-10-10)")
enddate_str = input("When is your deadline? e.g.(2017-10-11)")
startdate_dt = datetime.strptime(startdate_str,"%Y-%m-%d").date()
enddate_dt = datetime.strptime(enddate_str,"%Y-%m-%d").date()
numstudydays = enddate_dt - startdate_dt
print (numstudydays.days) # prints 1 for example inputs
Recommended links
The various kind of ways to format a string:
https://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior

Categories