Date & Time
什么是Tick?
时钟内部是以秒为单位的浮点数。自1970年1月1日12:AM开始,时间的特定瞬时以秒为单位。
Python中有一个特定的时间模块可以提供时间相关的功能,用于在时间格式间转换。Time.time()返回当前的系统时间,单位tick。
例子
import time; # This is required to include time module.
ticks = time.time()
print("Number of ticks since 12:00am, January 1, 1970:", ticks)
执行结果
Number of ticks since 12:00am, January 1, 1970: 1584447625.1085
使用tick做日期转换很简单。但是不能显示纪元之前的日期。在遥远的未来,日期也不能以这种方式表示 - 对UNIX和WIndows系统时间的截止点在2038年。
什么是时间元组(Tuple)
Python的很多时间函数以9个数字的元组形式处理时间,如下
Index | Field | Values |
---|---|---|
0 | 4-digit year | 2008 |
1 | Month | 1 to 12 |
2 | Day | 1 to 31 |
3 | Hour | 0 to 23 |
4 | Minute | 0 to 59 |
5 | Second | 0 to 61(60 或61是闰秒) |
6 | Day of Week | 0 to 6 (0 is Monday) |
7 | Day of year | 1 to 366 (Julian day) |
8 | Daylight savings | -1, 0, 1 means library determines DST |
Tuple time 与 struct_time一样
获得当前的时间
将纪元以来的时间(以秒为单位)瞬间转换成时间元组。
import time
localtime = time.localtime(time.time())
print("Local current time :", localtime)
执行结果
Local current time : time.struct_time(tm_year=2020, tm_mon=3, tm_mday=17, tm_hour=20, tm_min=42, tm_sec=56, tm_wday=1, tm_yday=77, tm_isdst=0)
获取格式化的时间
可以根据需求设置时间格式,但是最简单的可读时间格式是asctime()
import time
localtime = time.asctime( time.localtime(time.time()) )
print("Local current time :", localtime)
执行结果
Local current time : Tue Mar 17 20:46:30 2020
获取一个月的日历
calendar模块提供一系列方法展示以月和年显示的日历。
import calendar
cal = calendar.month(2020, 3)
print("Here is the calendar:")
print(cal)
执行结果
Here is the calendar:
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
Time和Calendar模块还提供很多方法,详见
https://www.tutorialspoint.com/python/python_date_time.htm