如何在python中分辨星期和天的日期差异?

时间:2018-06-29 21:57:24

标签: python datetime

我有一个这样的作业:

”-要求用户输入项目的截止日期,

-告诉他们完成项目需要多少天,

-将答案作为周和日的组合。”

我被困在第三点。 到目前为止,我的代码是这样的:

import datetime

deadlineInput = input ("What's the deadline for your project? (dd/mm/yyyy):")

deadline = datetime.datetime.strptime(deadlineInput, '%d/%m/%Y').date()

currentDate = datetime.date.today()

daysLeft = deadline - currentDate

print("You have " + str(daysLeft) + " left until the deadline")

谢谢。

1 个答案:

答案 0 :(得分:0)

使用f字符串,因为它将变量更改为字符串并且易于阅读。 因此,而不是

print("You have " + str(daysLeft) + "days left until the deadline")

您可以使用,它将把daysLeft更改为字符串。

print(f"You have {daysLeft} days left until the deadline")

还添加此代码以帮助获得日子。

#convert to days so you don't have the timestamp
daysLeft = daysLeft.days

因此它应该看起来像

import datetime

deadlineInput = input ("What's the deadline for your project? (dd/mm/yyyy):")

deadline = datetime.datetime.strptime(deadlineInput, '%d/%m/%Y').date()

currentDate = datetime.date.today()

daysLeft = deadline - currentDate

#convert to days so you don't have the timestamp
daysLeft = daysLeft.days

#Todo: homework
weeks = # calculate weeks from daysLeft using %
days = # calculate remainder from daysLeft using //

print(f"You have {weeks} weeks and {days} days left until the deadline")

然后返回并重构以删除camelCase并转换为snake_case例如daysLeft至days_left