Take a look at my code:
def convert_date(date_int):
month = int(date_int / 1000000)
date_int = int(date_int - 1000000 * month)
days = int(date_int / 10000)
date_int = int(date_int - 10000 * days)
year = date_int
return days, month, year
print("*This part*".format(convert_date(
int(input("Enter a date in the format MMDDYYYY: ")))))
That "this part" is the part that I dont know how to phrase to print a new line like this from user input “05102017”:
10/05/2017
Also I would appreciate if someone could suggest a better way to manipulate this user input😢
I would strongly suggest you use the datetime library.
But if you want to do it by simply manipulating a string from user input, you don't need the "convert_date" function. You can simply do:
input_date = input("Enter a date in the format MMDDYYYY: ")
print("{}/{}/{}".format(input_date[:2], input_date[2:4], input_date[4:]))
>>> date = int(input("Enter a date in the format MMDDYYYY: "))
Enter a date in the format MMDDYYYY: 05102017
>>> date = convert_date(date) # your function
>>> date
(10, 5, 2017)
>>> print("{}/{}/{}".format(date[0], date[1], date[2]))
10/5/2017
Related
Im a beginner and we have to do a lab assignment, basically the instructions say we have to enter the month and day of someones birthday as a single number (I.E. june 28 would be 628) then we have to print the month and the day individually (mainly where my problem lies), then give them their birthdate in xx/xx/2014.
the only way i can think to get the day is to take the original number (628) then subtract the month (which is the original/100 and formated to have no decimals) but i cant figure out how to do so
month_and_day = int(input ("Enter birthday as single number: "))
month = month_and_day / 100
print("month: ", format (month, "2.0f"))
print("day: ", month_and_day - format (month * 100, "2.0f"))
print("birthdate is: ", format (month, "0.2f"),"/", format (day, "0.2f"),"/ 2014")
strong text
The problem is here:
print("day: ", month_and_day - format (month * 100, "2.0f"))
month_and_day is of type int but format (month * 100, "2.0f") returns a string, and you can't subtract a string from an int
Since what you want is converting a number such as 628 to month and day to give them their birthdate like 6/28/2014.
I suggest that you can use time.strptime to convert do it, like this:
>>> s='628'
>>> t=time.strptime(s, '%m%d')
>>> t.tm_mon
6
>>> t.tm_mday
28
So your program can be:
import time
month_and_day = input ("Enter birthday as single number: ")
birthday=time.strptime(month_and_day, '%m%d')
month = birthday.tm_mon
day = birthday.tm_mday
print("birthdate is: ", format (month, "0.2f"),"/", format (day, "0.2f"),"/ 2014")
You don't have to construct everything by yourself, if there is a standard library for you purpose, use it.
I need to find the difference between two dates in terms of days by getting date as a user input. I tried to get date using raw_input but I'm getting an error. I'm using 2.7 version of python.
import time
from datetime import date
day1 = int(raw_input("enter the date in this format (yyyy:mm:dd)")
day2 = int(raw_input("enter the date in this format (yyyy:mm:dd)")
diff = day2-day1
print diff
You'll need to parse those dates into something a little more meaningful. Use the datetime.datetime.strptime() method:
from datetime import datetime
day1 = raw_input("enter the date in this format (yyyy:mm:dd)")
day2 = raw_input("enter the date in this format (yyyy:mm:dd)")
day1 = datetime.strptime(day1, '%Y:%m:%d').date()
day2 = datetime.strptime(day2, '%Y:%m:%d').date()
diff = day2 - day1
print diff.days
The datetime.datetime.date() method returns just the date portion of the resulting datetime object.
If you are expecting the input in the form "yyyy:mm:dd", you cannot simply cast it to int.
Besides strptime, you can parse the input by yourself.
day1 = [int(i) for i in raw_input('...').split(':')]
d1 = datetime.date(*day1)
day2 = [int(i) for i in raw_input('...').split(':')]
d2 = datetime.date(*day2)
diff = d2 - d1
print diff.days
Thanks to #JF Sebastian, even simpler way using lambda by defining:
str2date = lambda s: datetime.date(*map(int, s.split(':')))
Simply call:
date = str2date(raw_input('...'))
from datetime import date
import datetime
date1= datetime.date.today()
date_1=print(date1.strftime("The date of order: %d/%m/%Y"))
year = int(input('Enter a year: '))
month = int(input('Enter a month: '))
day = int(input('Enter a day: '))
date2 = datetime.date(year, month, day)
date_2= print(date2.strftime("Payment due date: %d/%m/%Y"))
difference=(date2-date1).days
print("The number of days for payment is: ", difference)
Its a program that allows a the user to find the difference between today's date and the input date from the user, in DAYS
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)
I am new to python and only know the most basic level.
I am supposed to allow input of a date in the form of dd/mm/yyyy and convert it to something like 26 Aug, 1986.
I am stuck as to how to convert my month(mm) from numbers to words.
Below is my current code, hope you can help me.
** please do not suggest using calendar function, we are supposed to use dict to solve this question.
Thank you (:
#allow the user to input the date
date=raw_input("Please enter the date in the format of dd/mm/year: ")
#split the strings
date=date.split('/')
#day
day=date[:2]
#create a dictionary for the months
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
#month
month=date[3:5]
if month in monthDict:
for key,value in monthDict:
month=value
#year
year=date[4:]
#print the result in the required format
print day, month, "," , year
Use Python's datetime.datetime! Read using my_date = strptime(the_string, "%d/%m/%Y"). Print it using my_date.strftime("%d %b, %Y").
Visit: http://docs.python.org/2/library/datetime.html#strftime-and-strptime-behavior
Example:
import datetime
input = '23/12/2011'
my_date = datetime.datetime.strptime(input, "%d/%m/%Y")
print my_date.strftime("%d %b, %Y") # 23 Dec, 2011
date = raw_input("Please enter the date in the format of dd/mm/year: ")
date = date.split('/')
day = date[0] # date is, for example, [1,2,1998]. A list, because you have use split()
monthDict = {1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun',
7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
month = date[1] # Notice how I have changed this as well
# because the length of date is only 3
month = monthDict[int(month)]
year = date[2] # Also changed this, otherwise it would be an IndexError
print day, month, "," , year
When run:
Please enter the date in the format of dd/mm/year: 1/5/2004
1 May , 2004
After you have done split, you don't need to use index like day=date[:2]. Simply use say = date[0]. Similarly no looping is required to match dictionary values. You can see the code below.
#allow the user to input the date
date=raw_input("Please enter the date in the format of dd/mm/year: ")
#split the strings
date=date.split('/')
#day
day=date[0]
#create a dictionary for the months
monthDict={1:'Jan', 2:'Feb', 3:'Mar', 4:'Apr', 5:'May', 6:'Jun', 7:'Jul', 8:'Aug', 9:'Sep', 10:'Oct', 11:'Nov', 12:'Dec'}
#month
monthIndex= int(date[1])
month = monthDict[monthIndex]
#year
year=date[2]
print day, month, "," , year
When you split your date string, you will only have three elements (0, 1, and 2):
>>> date=date.split('/')
>>> print date
['11', '12', '2012']
^ ^ ^
0 1 2
Thus, date[:2] will equal this:
>>> day=date[:2] # that is, date up to (but not including) position 2
>>> print day
['11', '12']
And date[4] will not exist, and neither will date[3:5].
In addition, you need to call your dictionary value like this:
>>> print monthDict[12]
Dec
So to print the day, month, year combination, you would want to do this:
>>> print date[0], monthDict[int(date[1])] + ", " + date[2]
11 Dec, 2012
You have to use int(date[0]) as your key in monthDict[int(date[0])] because you used integers as your dictionary keys. But your input (from the user) is a string, not integers.
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