Python 日期和时间操作

PythonPythonBeginner
立即练习

This tutorial is from open-source community. Access the source code

💡 本教程由 AI 辅助翻译自英文原版。如需查看原文,您可以 切换至英文原版

简介

在 Python 中,datetime 模块提供了用于处理日期和时间的类。该模块中的一个类是 date,它表示一个日期(年、月、日),并提供了各种处理日期的方法。另一个类是 timedelta,它表示两个日期或时间之间的持续时间或差值。


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("Python")) -.-> python/BasicConceptsGroup(["Basic Concepts"]) python(("Python")) -.-> python/DataStructuresGroup(["Data Structures"]) python(("Python")) -.-> python/FunctionsGroup(["Functions"]) python(("Python")) -.-> python/ModulesandPackagesGroup(["Modules and Packages"]) python(("Python")) -.-> python/PythonStandardLibraryGroup(["Python Standard Library"]) python/BasicConceptsGroup -.-> python/comments("Comments") python/DataStructuresGroup -.-> python/tuples("Tuples") python/FunctionsGroup -.-> python/function_definition("Function Definition") python/ModulesandPackagesGroup -.-> python/importing_modules("Importing Modules") python/ModulesandPackagesGroup -.-> python/using_packages("Using Packages") python/ModulesandPackagesGroup -.-> python/standard_libraries("Common Standard Libraries") python/PythonStandardLibraryGroup -.-> python/date_time("Date and Time") subgraph Lab Skills python/comments -.-> lab-13613{{"Python 日期和时间操作"}} python/tuples -.-> lab-13613{{"Python 日期和时间操作"}} python/function_definition -.-> lab-13613{{"Python 日期和时间操作"}} python/importing_modules -.-> lab-13613{{"Python 日期和时间操作"}} python/using_packages -.-> lab-13613{{"Python 日期和时间操作"}} python/standard_libraries -.-> lab-13613{{"Python 日期和时间操作"}} python/date_time -.-> lab-13613{{"Python 日期和时间操作"}} end

若干天前

你的任务是编写一个名为 days_ago(n) 的函数,它接受一个整数 n 作为参数,并返回从今天起 n 天前的日期。

要解决这个问题,你需要使用 datetime 模块中的 date 类来获取当前日期,并使用 timedelta 类从当前日期中减去 n 天。

from datetime import timedelta, date

def days_ago(n):
  return date.today() - timedelta(n)
days_ago(5) ## date(2020, 10, 23)

总结

在这个挑战中,你学习了如何使用 datetime 模块中的 datetimedelta 类来计算从今天起 n 天前的日期。在 Python 中处理日期和时间时,这是一项很有用的技能。