介绍
Datetime 模块是time模块的再次封装,提供了更多的接口。主要是日期和时间的解析,格式化及运算。
其他关于时间的模块:
time - basic
calendar - basic
pytz - 关于time zones
dateutil - extension of datetime
常用操作
Times类
import datetime t = datetime.time(1,2,3) # 01:02:03 print(t) # 语法: datetime.time(hour,min,sec) print("hour:", t.hour) # hour: 1 print(‘minute: ‘, t.minute) # minute: 2 print(‘second:‘,t.second) print(‘microsecond:‘,t.microsecond) print(‘tzinfo:‘, t.tzinfo) # time zone info print(‘earlist:‘, datetime.time.min) #earlist: 00:00:00 print(‘latest:‘, datetime.time.max) #latest: 23:59:59.999999 print(‘resolution:‘, datetime.time.resolution) # resolution: 0:00:00.000001
注意, microsecond毫秒不能用float模式来表示,只能整数。
Dates类
date类主要用于表示calendar date。属性包括year, month and day。
import datetime today = datetime.date.today() print(today) # 2017-08-20 print(‘ctime:‘, today.ctime()) # ctime: Sun Aug 20 00:00:00 2017 print(‘ordinal:‘, today.toordinal()) # ordinal: 736561 print("year:", today.year) # year: 2017 print(‘month:‘,today.month) # month: 8 print(‘day:‘, today.day) # day: 20 tuple_today = today.timetuple() print(tuple_today) # time.struct_time(tm_year=2017, tm_mon=8, tm_mday=20, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=232, tm_isdst=-1) print(tuple_today.tm_year) # 提取struct_time里的元素
timedeltas
Date Arithmetic
Comparing values
Combining dates and times
Formatting and parsing
Time zones
时间: 2024-10-19 02:56:54