我必须以(mm / dd / yyyy)形式输入日期。所以,在报告这个日期时,我会有类似于05/13/1999的内容,如何从月份中删除零。我希望它能够读取像11/12/1999那样的两位数月份
from functionax import disp_bday
name = raw_input("Enter name: ")
s = date = raw_input("Enter dob (mm/dd/yyyy): ")
x = month = int((s[0:1])
year = s[6:10]
print disp_bday(name, month, year)
functionax低于
from datetime import date
def display_birthday_wishes(name, month, year):
p = current_year = date.today().year
current_age = (int(p)-int(year))
if month == 1:
month = 'Carnations'
elif month == 2:
month = 'Primroses'
elif month == 3:
month = 'Daffodils'
elif month == 4:
month = 'Sweet peas'
elif month == 5:
month = 'Hawthorn flowers'
elif month == 6:
month = 'Roses'
elif month == 7:
month = 'Water lilies'
elif month == 8:
month = 'Poppies'
elif month == 9:
month = 'Asters'
elif month == 10:
month = 'Calendulas'
elif month == 11:
month = 'Chrysanthemums'
elif month == 12:
month = 'Holly flowers'
return "Hi, " + name + ". You are " + str(current_age) +\
" years old this year! Here's a bouquet of "+month+" for you!"
答案 0 :(得分:0)
这听起来好像你想使用Regular Expression:
import re
m = re.match(r'(\d{1,2})/(\d{1,2})/(\d{4})', date)
if m:
print disp_bday(m.groups())
else:
print "invalid input"
有关使用的表达式
的更多信息,请查看here答案 1 :(得分:0)
您在第4行缺少右括号。
你可以这样做:
from datetime import date
flowers = [
'Carnations',
'Primroses',
'Daffodils',
'Sweet peas',
'Hawthorn flowers',
'Roses',
'Water lilies',
'Poppies',
'Asters',
'Calendulas',
'Chrysanthemums',
'Holly flowers'
]
def display_birthday_wishes(name, month, year):
p = date.today().year
current_age = (int(p)-int(year))
return "Hi, " + name + ". You are " + str(current_age) +\
" years old this year! Here's a bouquet of "+ flowers[month-1] +" for you!"
name = raw_input("Enter name: ")
foo = raw_input("Enter dob (mm/dd/yyyy): ")
month, d, year = foo.split("/")
if month[0] == "0":
month = int(month[1:])
print display_birthday_wishes(name, month, year)
请注意,我必须修改前面的示例,以便不提date
(我只是将该变量缩短为d
),否则它会干扰date
函数。
答案 2 :(得分:0)
不要自己解析状态,而是使用内置的datetime
模块
>>> dt = datetime.strptime("05/13/1999", "%m/%d/%Y")
>>> dt.month
5
>>> dt = datetime.strptime("11/12/1999", "%m/%d/%Y")
>>> dt.month
11
所以,只需替换代码
x = month = int((s[0:1])
year = s[6:10]
到
dt = datetime.strptime(date , "%m/%d/%Y")
x = month = dt.month
year = dt.year
答案 3 :(得分:0)
我没有在python2中试过这个,但是如果你使用的是python3
from datetime import date, datetime as dt
day, month, year = "05/13/1999".split("/")
old_date = date(int(year), int(day), int(month))
new_date = dt.strftime(old_date, "{0}/{1}/{2}".format(old_date.month, \
old_date.day, old_date.year))
答案 4 :(得分:0)
在要剥离0的项目之前添加-
。
datetime.strptime("05/13/1999", "%m/%d/%Y").strftime("%-m/%d/%Y")