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.
Related
How would I go about designing a Python program which takes in a date from the user, a date that looks like this 3/13/17, and turns it into a date which looks like this 2017.3.13?
You can split the string by using the str.split method like this:
s = "3/13/17"
month, day, year = s.split("/")
print(f"20{year}.{month}.{day}")
Python will automatically assign the splitted values to the variables month, day, and year
Get the date as text and then convert it to date with the format you would like. or get the date as a number (month, date and year ) separately and make it as a date.
Example:
my_string = str(input('Enter date(yyyy-mm-dd): '))
my_date = datetime.strptime(my_string, "%Y-%m-%d")
I have a question: How to use "strip" function to slice a date like "24.02.1999"?
The output should be like this '24', '02', '1999'.
Can you help to solve this?
You can do like this
>>> stri="24.02.1999"
>>> stri.split('.')
['24', '02', '1999']
>>>
strip is used to remove the characters. What you meant is split. For your code,
date = input('Enter date in the format (DD.MM.YY) : ')
dd, mm, yyyy = date.strip().split('.')
print('day = ',dd)
print('month = ',mm)
print('year = ',yyyy)
Output:
Enter date in the format (DD.MM.YY) : 24.02.1999
day = 24
month = 02
year = 1999
You need to use split() not strip().
strip() is used to remove the specified characters from a string.
split() is used to split the string to list based on the value provided.
date = str(input()) # reading input date in dd.mm.yyyy format
splitted_date = date.split('.') # splitting date
day = splitted_date[0] # storing day
month = splitted_date[1] # storing month
year = splitted_date[2] # storing year
# Display the values
print('Date : ',date)
print('Month : ',month)
print('Year : ',year)
You can split date given in DD.MM.YYYY format like this.
Instead of splitting the string, you should be using datetime.strptime(..) to convert the string to the datetime object like:
>>> from datetime import datetime
>>> my_date_str = "24.02.1999"
>>> my_date = datetime.strptime(my_date_str, '%d.%m.%Y')
Then you can access the values you desire as:
>>> my_date.day # For date
24
>>> my_date.month # For month
2
>>> my_date.year # For year
1999
Here you go
date="24.02.1999"
[dd,mm,yyyy] = date.split('.')
output=(("'%s','%s','%s'") %(dd,mm,yyyy))
print(output)
alternate way
date="24.02.1999"
dd=date[0:2]
mm=date[3:5]
yyyy=date[6:10]
newdate=(("'%s','%s','%s'") %(dd,mm,yyyy))
print(newdate)
one more alternate way
from datetime import datetime
date="24.02.1999"
date=datetime.strptime(date, '%d.%m.%Y')
date=(("'%s','%s','%s'") %(date.day,date.month,date.year))
print(date)
Enjoy
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
I'm trying to enter a date in Python but sometimes I don't know the exact day or month. So I would like to record only the year. I would like to do something like:
datetime.date(year=1940, month="0 or None", day="0 or None")
Is there a code for doing this? Or if not, how would you manage to deal with this problem?
Unfortunately, you can't pass 0 because there is no month 0 so you'll get ValueError: month must be in 1..12, you cannot skip the month or the day as both are required.
If you do not know the exact year or month, just pass in 1 for the month and day and then keep only the year part.
>>> d = datetime.date(year=1940, month=1, day=1)
>>> d
datetime.date(1940, 1, 1)
>>> d.year
1940
>>> d = datetime.date(year=1940, month=1, day=1).year
>>> d
1940
The second statement is a shorthand for the first.
However, if you want to just store the year, you don't need a datetime object. You can store the integer value separately. A date object implies month and day.
Pandas has Period class where you don't have to supply day if you don't know that:
import pandas as pd
pp = pd.Period('2013-12', 'M')
print pp
print pp + 1
print pp - 1
print (pp + 1).year, (pp + 1).month
Output:
2013-12
2014-01
2013-11
2014 1
How can I print the next year if the current year is given in python using the simplest code, possibly in one line using datetime module.
Both date and datetime objects have a year attribute, which is a number. Just add 1:
>>> from datetime import date
>>> print date.today().year + 1
2013
If you have the current year in a variable, just add 1 directly, no need to bother with the datetime module:
>>> year = 2012
>>> print year + 1
2013
If you have the date in a string, just select the 4 digits that represent the year and pass it to int:
>>> date = '2012-06-26'
>>> print int(date[:4]) + 1
2013
Year arithmetic is exceedingly simple, make it an integer and just add 1. It doesn't get much simpler than that.
If, however, you are working with a whole date, and you need the same date but one year later, use the components to create a new date object with the year incremented by one:
>>> today = date.today()
>>> print date(today.year + 1, today.month, today.day)
2013-06-26
or you can use the .replace function, which returns a copy with the field you specify changed:
>>> print today.replace(year=today.year + 1)
2013-06-26
Note that this can get a little tricky when today is February 29th in a leap year. The absolute, fail-safe correct way to work this one is thus:
def nextyear(dt):
try:
return dt.replace(year=dt.year+1)
except ValueError:
# February 29th in a leap year
# Add 365 days instead to arrive at March 1st
return dt + timedelta(days=365)
here is another simple way...
import datetime
x = datetime.datetime.now()
print(x.year+1)