Python 程序在运行的时候可能需要获得当前的时间。 在这个时候我们需要导入 datetime 包。 获得当前时间 例如,可以使用下面的代码获得当前的日期。 today = datetime.date.today() print("Today's date:", today) 在上面的代码中,将会输出: Today’s date: 2021-03-12 的内容。 格式化日期 当你获得日期对象后,你可以通过 strftime 函数来格式化日子。 today = datetime.date.today() print("日期对象格式化输出 1 =", today.strftime("%d/%m/%Y")) print("日期对象格式化输出 2 =", today.strftime("%B %d, %Y")) print("日期对象格式化输出 3 =", today.strftime("%m/%d/%y")) print("日期对象格式化输出 4 =", today.strftime("%b-%d-%Y")) 上面的代码将会将会对 date 对象按照输入格式进行格式化。 时间戳 可以考虑下下面的代码,下面的代码将会输出日期的时间戳。 now = datetime.datetime.now() print("当前时间戳:", now) 上面的代码,将会输出为:当前时间戳: 2021-03-12 10:40:02.982640 这样的格式。 如果你对时间函数还希望有些了解的话,你可以在导入 datetime 包后再进行测试。 https://www.ossez.com/t/python/13389