Reputation: 85
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?
Upvotes: 0
Views: 1857
Reputation: 5591
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
Upvotes: 0
Reputation: 48067
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
Upvotes: 0
Reputation: 11907
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.
Upvotes: 0
Reputation: 1357
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
Upvotes: 0
Reputation: 1943
You can do like this
>>> stri="24.02.1999"
>>> stri.split('.')
['24', '02', '1999']
>>>
Upvotes: 1