I'm trying to convert yyyy/mm/dd to dd/mm/yyyy, from integer inputs.
When i've changed the pattern inside the parethesis from datetime.date(year, month, day), to datetime.date(day, month, year), it returns an Value error.
def acc_expiration():
year = int(input('YEAR: '))
month = int(input('MONTH: '))
day = int(input('DAY: '))
exp_date = datetime.date(day, month, year)
return exp_date
ValueError: day is out of range for month
From the documentation:
class datetime.date(year, month, day)
This means you need to put the arguments in the right position, doesn't matter how you want to print it later.
This should work:
def acc_expiration():
year = int(input('YEAR: '))
month = int(input('MONTH: '))
day = int(input('DAY: '))
exp_date = datetime.date(year, month, day)
return exp_date
Now let's print it formatted in dd/mm/yyyy:
d = acc_expiration()
f = d.strftime('%d/%m/%Y')
print(f) # prints it formatted dd/mm/yyyy
Your value error is because you are giving a year integer (integer bigger than 31) to the day argument, and for the year you are giving the day integer.
You are confusing the object from its presentation.
Look at the Python docs for Datetime (here)
The correct sequence for datetime.date is class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
Once you have a datetime object, you can format the output of it in a variety of ways to suit your needs.
Does that help?
Related
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.
I'm trying to make a program that takes a date inputted by the user in 'yyyy mm dd' format and see how many days that input is from today. I have no idea how to do this but if u can help that would be great.
input("This is a function to find the difference between today and a date
you enter. Enter the date in this format: 'yyyy mm dd' ")
This should work
import datetime
today = datetime.date.today()
year = int(input('Enter a year')) #input the needed year
month = int(input('Enter a month')) #input the needed month
day = int(input('Enter a day')) #input the needed day
neededdate = datetime.date(year, month, day)
days_remaining = neededdate - today
print(days_remaining.days)
I edited to input date, month and year.
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.
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
I would like to write a function that takes a date entered by the user, stores it with the shelve function and prints the date thirty days later when called.
I'm trying to start with something simple like:
import datetime
def getdate():
date1 = input(datetime.date)
return date1
getdate()
print(date1)
This obviously doesn't work.
I've used the answers to the above question and now have that section of my program working! Thanks!
Now for the next part:
I'm trying to write a simple program that takes the date the way you instructed me to get it and adds 30 days.
import datetime
from datetime import timedelta
d = datetime.date(2013, 1, 1)
print(d)
year, month, day = map(int, d.split('-'))
d = datetime.date(year, month, day)
d = dplanted.strftime('%m/%d/%Y')
d = datetime.date(d)+timedelta(days=30)
print(d)
This gives me an error:
year, month, day = map(int, d.split('-'))
AttributeError: 'datetime.date' object has no attribute 'split'
Ultimately what I want is have 01/01/2013 + 30 days and print 01/30/2013.
Thanks in advance!
The input() method can only take text from the terminal. You'll thus have to figure out a way to parse that text and turn it into a date.
You could go about that in two different ways:
Ask the user to enter the 3 parts of a date separately, so call input() three times, turn the results into integers, and build a date:
year = int(input('Enter a year'))
month = int(input('Enter a month'))
day = int(input('Enter a day'))
date1 = datetime.date(year, month, day)
Ask the user to enter the date in a specific format, then turn that format into the three numbers for year, month and day:
date_entry = input('Enter a date in YYYY-MM-DD format')
year, month, day = map(int, date_entry.split('-'))
date1 = datetime.date(year, month, day)
Both these approaches are examples; no error handling has been included for example, you'll need to read up on Python exception handling to figure that out for yourself. :-)
Thanks. I have been trying to figure out how to add info to datetime.datetime(xxx) and this explains it nicely. It's as follows
datetime.datetime(year,month, day, hour, minute, second) with parameters all integer. It works!
Use the dateutils module
from dateutil import parser
date = parser.parse(input("Enter date: "))
you can also use
import datetime
time_str = input("enter time in this format yyyy-mm-dd")
time=datetime.datetime.strptime(time_str, "%Y-%m-%d")
datetime.datetime.strptime() strips the given string in the format you give it.
Check the library as
import datetime
and follow syntax
date = datetime.datetime(2013, 1, 1)