Python提供了带有实际日期和时间的 datetime 模块。在实际的应用程序中,无涯教程需要处理日期和时间。能够计划Python脚本在特定时间运行。
在Python中,日期不是数据类型,但是可以通过导入以 datetime,time和calendar 命名的模块来使用date对象。
在本教程的这一部分中,将讨论如何在Python中使用日期和时间对象。
datetime 类分为六个主要类。
在Python中,从1970年1月1日凌晨12点开始计时。模块时间的函数 time()返回自1970年1月1日凌晨12点以来Tick总数。被视为测量时间的最小单位。
import time; #prints the number of ticks spent since 12 AM, 1st January 1970 print(time.time())
输出:
1585928913.6519969
时间模块的localtime()函数用于获取当前时间元组. 考虑下面的例子.
输出:
time.struct_time(tm_year=2020, tm_mon=4, tm_mday=3, tm_hour=21, tm_min=21, tm_sec=40, tm_wday=4, tm_yday=94, tm_isdst=0)
时间被视为9个数字的元组。看一下时间元组的成员。
索引 | 属性 | 值 |
---|---|---|
0 | 年份 | 4位数字(例如2018) |
1 | 月 | 1到12 |
2 | 日 | 1到31 |
3 | 小时 | 0到23 |
4 | 分钟 | 0到59 |
5 | 秒 | 0到60 |
6 | 一周中的一天 | 0到6 |
7 | 一年中的一天 | 1至366 |
8 | 夏令时 | -1、0、1或-1 |
可以使用时间模块的 asctime()函数来格式化时间。它返回经过的时间元组的格式化时间。
输出:
Tue Dec 18 15:31:39 2018
时间模块的 sleep()方法用于在给定的时间内停止脚本的执行。输出将延迟浮动提供的秒数。
输出:
0 1 2 3 4
datetime 模块能够创建自定义日期对象,对日期执行各种操作,例如比较等。
要将日期用作日期对象,必须将 datetime 模块导入python源代码。
输出:
2020-04-04 13:18:35.252578
可以在要为其创建日期对象的datetime构造函数中绕过所需的日期来创建日期对象。
import datetime #returns the datetime object for the specified date print(datetime.datetime(2020,04,04))
输出:
2020-04-04 00:00:00
还可以指定时间和日期,以创建datetime对象. 考虑下面的例子.
import datetime #returns the datetime object for the specified time print(datetime.datetime(2020,4,4,1,26,40))
输出:
2020-04-04 01:26:40
在上面的代码中,按顺序传递了 datetime()函数的年,月,日,时,分和毫秒属性。
可以使用诸如>,> =,<和<=的比较运算符来比较两个日期。
from datetime import datetime as dt #比较时间。如果时间在上午8点至下午4点之间,那么它打印 Working hours,否则它打印fun hours if dt(dt.now().year,dt.now().month,dt.now().day,8)<dt.now()<dt(dt.now().year,dt.now().month,dt.now().day,16): print("Working hours....") else: print("fun hours")
输出:
fun hours
Python提供了一个日历对象,其中包含使用日历的各种方法。
import calendar; cal = calendar.month(2020,3) #printing the calendar of December 2018 print(cal)
输出:
March 2020 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31
日历模块的prcal()方法用于打印全年的日历。必须将要打印日历的年份传递给此方法。
链接:https://www.learnfk.comhttps://www.learnfk.com/python3/python-date.html
来源:LearnFk无涯教程网
输出:
祝学习愉快!(内容编辑有误?请选中要编辑内容 -> 右键 -> 修改 -> 提交!)
Spring Cloud 微服务项目实战 -〔姚秋辰(姚半仙)〕