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
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 pretty new to python and I'm currently trying to write a code for a small project. My problem is that when I execute my code I get the date + time and I'm only interested in the date. I've tried googling the problem but haven't found a solution for using datetime and ephem together (I have to use ep.date(datetime(year, month, day)) so I can use the input date with other dates that I get from ephem).
This is a small example code of what I'm doing:
from datetime import datetime
import ephem as ep #explanation
input_date =input("Please enter the date you you'd like to know the moon phase for in the YYYY-MM-DD format: " )
year, month, day = map(int, input_date.split('-'))
datetime(int(year), int(month), int(day))
new_date = ep.date(datetime(year, month, day))
print(new_date)
And this is my output:
https://i.stack.imgur.com/0VJQM.png
If you click on the link you'll see that I get 2020/2/2 00:00:00 for the input 2020-2-2, it doesn't make my code stop working, but because I'll display this date quite often, I'd like to remove the time and only have the date.
If you just need to display the date and don't need further calculations, you can convert the ephem Date type back into a Python datetime type, then convert the Python datetime into a date.
from datetime import datetime
import ephem as ep #explanation
input_date =input("Please enter the date you you'd like to know the moon phase for in the YYYY-MM-DD format: " )
year, month, day = map(int, input_date.split('-'))
ephem_date = ep.date(datetime(year, month, day))
python_date_only = new_date.datetime().date()
print(python_date_only)
You can use ‘from datetime import date’ instead of ‘datetime’
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)
If I have a hard coded date, how can I compare it to a date that is given by the user?
I want to eventually compare a persons birthday to see how old they are. Can someone point me in the right direction?
You'll want to use Python's standard library datetime module to parse and convert the "date given by the user" to a datetime.date instance and then subtract that from the current date, datetime.date.today(). For example:
>>> birthdate_str = raw_input('Enter your birthday (yyyy-mm-dd): ')
Enter your birthday (yyyy-mm-dd): 1981-08-04
>>> birthdatetime = datetime.datetime.strptime(birthdate_str, '%Y-%m-%d')
>>> birthdate = birthdatetime.date() # convert from datetime to just date
>>> age = datetime.date.today() - birthdate
>>> age
datetime.timedelta(11397)
age is a datetime.timedelta instance, and the 11397 is their age in days (available directly via age.days).
To get their age in years, you could do something like this:
>>> int(age.days / 365.24)
31
I need help with a program.
How do I add 3 weeks (21 days) to any given date when the user can control the date?
The user will enter the date YYYY-MM-DD.
Below I'm trying to locate the hyphen and make sure there is only 2. This is what I have so far but all it does is repeat itself, can someone tell me where I went wrong ?:
date = raw_input("Enter date: ")
i = 0
while i <= len(date):
if date[i] != "-":
i = i + 1
print date
Now I'm picking out year, month, day. Is there an easier way to do this cause I need to account for the change months etc ?
year = date[0:4]
month = date[5:7]
day = date[9:11]
thanks
Use datetime module to the task. You create a datetime aware object and add 21 days timedelta object to it.
>>> import datetime
>>> u = datetime.datetime.strptime("2011-01-01","%Y-%m-%d")
>>> d = datetime.timedelta(days=21)
>>> t = u + d
>>> print(t)
2011-01-22 00:00:00
You can use a datetime.timedelta object to represent 3 weeks and then just add that to the datetime object that represents the user's input.
import datetime
date = raw_input("Enter date: ")
aDate = datetime.datetime.strptime(date,"%Y-%m-%d")
threeWeeks = datetime.timedelta(weeks = 3)
print aDate + threeWeeks
See http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior for details about using the strptime method.
Try this, I am sure its the shortest and easiest way to go
from dateutil.relativedelta import relativedelta
period = date.today() + relativedelta(weeks=+1)
you can use datetime.strptime to get input from user as date
from datetime import datetime
i = str(raw_input('date'))
try:
dt_start = datetime.strptime(i, '%Y, %m, %d')
except ValueError:
print "Incorrect format"
and then to add 3 weeks (21 days)
dt_start = dt_start + datetime.timedelta(days=21)
There you go