如何从日期中删除时间?(Python)



我对Python和编程都是新手。我在想,怎样才能把时间从日期中去掉呢?下面是我的代码:

import datetime
currentDate = datetime.date.today()
userInput = input("Please enter your birth date? (dd/mm/yyyy) )")
birthdate = datetime.datetime.strptime(userInput, "%d/%m/%Y").date()
days = birthdate - currentDate
print('You were born ' +str(days), 'ago')

现在,如果我输入我的出生日期是14/10/1996,它会输出"You were born 6806 days, 00:00:00 ago."我希望它只输出日期,这样它就会像这样结束"You were born 6806 days ago."

任何帮助都将非常感激!

days是一个timedelta对象,您可以直接访问它的days组件:

>>> days.days # -6806

您实际要求做的是从timedelta对象的__str__中删除时间,而不是datetime对象。要做到这一点的唯一方法是构建自己的字符串- timedelta的输出格式是不可配置的。

print('You were born {} days ago'.format(days.days))

相关内容

  • 没有找到相关文章

最新更新