我正在编写一个python程序,该程序接受出生日期(mm-dd-yyyy)和天数(例如:5000)的输入,并打印出具有出生日期的人将达到该天数的日期。例如,如果我输入"05-12-1960";和"30000",我应该得到07-01-2042。到目前为止,我已经能够获得出生日期和天数的输入函数:
birthdate = input("Enter your date of birth (mm-dd-yyyy): ")
days = input("Enter a number of days: ")
我最近刚接触python,所以我仍在尝试学习其他函数,如str, input, int等。我是从计数器或if/else语句开始吗?谢谢你的反馈。
您可以使用datetime模块将日期字符串转换为日期对象,然后使用timedelta
将其增加一些天数。
错误处理也很重要。如果您使用用户输入字符串执行这些操作,那么添加一些验证用户实际输入了有效的日期和整数也很重要,否则如果用户输入了无效的条目,程序将崩溃。
下面是一个例子:
import datetime
def get_birthday():
"""Get the birthday, catch if it is not a valid date and ask again"""
while True:
birthdate = input("Enter your date of birth (mm-dd-yyyy): ")
try:
return datetime.datetime.strptime(birthdate, "%m-%d-%Y")
except ValueError:
print(f"'{birthdate}' is not a valid date, try again")
def get_num_days():
"""Get the number of days, catch if it is not a valid integer and ask again"""
while True:
days = input("Enter a number of days: ")
try:
return int(days)
except ValueError:
print(f"'{days}' is not an integer, try again")
date = get_birthday()
num_days = get_num_days()
date += datetime.timedelta(days = num_days)
new_date_str = date.strftime("%m-%d-%Y")
print(f"The new date is {new_date_str}")
您可以使用datetime
来解析日期时间
import datetime
birthdate = input("Enter your date of birth (mm-dd-yyyy): ")
days = input("Enter a number of days: ")
birthdate = ''.join([birthdate[i] for i in (6, 7, 8, 9, 2, 0, 1, 2, 3, 4)]) # reorder the string to convert `mm-dd-yyyy` to `yyyy-mm-dd`
birthtime = datetime.datetime.fromisoformat(birthdate).timestamp() # get timestamp in seconds
time_after = birthtime + int(days)*86400
new = datetime.datetime.fromtimestamp(time_after)
# do things
print(f'It will be {new.year}, month {new.month} day {new.day}')
输出:Enter your date of birth (mm-dd-yyyy): 01-01-2022
Enter a number of days: 14
It will be 2022, month 1 day 15
[root@cscale-82-69 python]# cat dateime.py
from datetime import datetime
from datetime import timedelta
startdate = datetime.strptime("2022-5-1", "%Y-%m-%d")
print(startdate)
finaldate = startdate + timedelta(days=5000)
print(finaldate)
的示例输出[root@cscale-82-69 python]# python dateime.py
2022-05-01 00:00:00
2036-01-08 00:00:00
[root@cscale-82-69 python]#
在Python中,你应该开始学习Python标准库中可用的模块。对于您的任务,您可以使用datetime
模块。
from datetime import datetime, timedelta
# Your input functions
birthdate = input("Enter your date of birth (mm-dd-yyyy): ")
days = input("Enter a number of days: ")
# Using the calendar functions from datetime module
dateformat = '%m-%d-%Y'
# redefining a name is usually not a good practice
birthdate = datetime.strptime(birthdate, dateformat)
newdate = birthdate + timedelta(days = int(days))
print(newdate.strftime(dateformat))