python时间处理:datetime,time,calendar
datetime模块
一,两个常量:
MINYEAR,最小年份1;
MAXYEAR,最大年份9999
二,五个类:
1.datetime.date(year, month, day):表示日期的类。
1.1 date类型的具体属性:
min:最小date---0001-01-01。
max:最大date---9999-12-31。
resolution:date类型的最小单位---1 day, 0:00:00。
year:date对象对应的年,int类型。
month:date对象对应的月,int类型。
day:date对象对应的日,int类型。
1.2 date类型的具体方法:
today():返回本地当前的date。
fromtimestamp(timestamp):根据给定的timestamp时间戳返回对应的date。
replace(year, month, day):生成一个新的date,用指定的年月日替换。
timetuple():回日期对应的time.struct_time对象。
weekday():返回星期,如果是星期一是返回0,返回int类型。
isoweekday():返回标准的星期,星期一是1,返回int类型。
isocalendar():返回(ISO year, ISO week number, ISO weekday)元组。
isoformat():返回yyyy-mm-dd的标准日期字符串形式。
ctime():返回一个日期字符串,如'Wed Dec 4 00:00:00 2002'。
strftime(format):自定义格式化日期字符串。
1.3 date类型支持的操作:
操作
|
说明
|
date2 = date1 + timedelta | 一个日期加上一个时间间隔等于一个新时间 |
date2 = date1 - timedelta
|
一个时间减去一个时间间隔等于一个新时间
|
timedelta = date2 - date1
|
两个时间相减等于一个时间间隔
|
date1 > date2
|
比较两个时间
|
2.datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]]):表示时间的类,tzinfo表示时区。
2.1 time类型具体属性:
min:最小的time类型。
max:最大的time类型。
resolution:time类型的最小单位,两个time对象间不能加减。
hour:范围在24之内的int类型,对应时。
minute:范围在60内的int类型,对应分。
second:范围在60内的int类型,对应秒。
microsecond:范围在1000000内的int类型,对应微妙。
tzinfo:时区信息,默认为None。
2.2 time类型具体方法:
replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]):通过各个参数替换time中的时分秒等信息。
isoformat():返回标准的时间字符串,HH:MM:SS.mmmmmm,如16:02:00.000999.
strftime(format):自定义格式时间字符串。
utcoffset():如果tzinfo是None,则返回None。如果不是就返回tzinfo.utcoffset(None)。
dst():如果tzinfo是None,则返回None。如果不是就返回tzinfo.dst(None)。
tzname():如果tzinfo是None,则返回None。如果不是就返回tzinfo.tzname(None)。
注意:time之间不能进行加减,可以进行比较>,<,=
3.datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]):表示日期时间。
3.1 datetime类型具体属性:
date类型和time类型的属性datetime都具备:min,max,resolution,year,month,day,hour,minute,second,microsecond,tzinfo。
3.2 datetime类型具体方法:
today():返回当前本地的datetime。此时的tzinfo是None。
now([tzinfo]):返回当前本地的datetime。
utcnow():返回utc时区的当前的datetime。
fromtimestamp(timestamp[, tzinfo]):根据给定的timestamp时间戳返回对应的datetime。
utcfromtimestamp(timestamp):根据给定的timestamp时间戳返回对应的datetime,时区为标准UTC时区。
combine(date, time):根据date和time组成一个datetime。
strptime(date_string, format):根据format格式把date_string转换成一个datetime。
还有包括date和time的方法datetime都具备,如strftime(format)等。
3.3 datetime类型支持的操作:
操作
|
说明
|
datetime2 = datetime1 + timedelta | 一个datetime加上一个时间间隔等于一个新datetime |
datetime2 = datetime1 - timedelta
|
一个datetime减去一个时间间隔等于一个新datetime
|
timedelta = datetime2 - datetime1
|
两个datetime相减等于一个时间间隔
|
datetime1 > datetime2
|
比较两个datetime
|
4.datetime.timedelta([days[, seconds[, microseconds[, milliseconds[, minutes[, hours[, weeks]]]]]]]):表示时间间隔,即两个时间点之间的长度。
4.1 timedelta类型具体属性:
min:最小的timedelta,-999999999 days, 0:00:00
max:最大的timedelta,999999999 days, 23:59:59.999999
resolution:timedelta的最小单位,0:00:00.000001
属性
|
含义
|
范围
|
days
|
相差的天数,不包含seconds和microsecond |
-999999999 到 999999999
|
seconds
|
相差的秒杀,不计算days和microseconds
|
0 到 86399(一天不到一秒)
|
microseconds
|
相差的微妙,不计算days和seconds
|
0 and 999999
|
支持的操作
操作
|
结果
|
t1 = t2 + t3 |
|
t1 = t2 - t3
|
|
t1 = i * t2
|
|
t1 = t2 // 2
|
向下取整,余数部分被丢弃 |
+t1
|
|
-t1
|
取反操作,等价于timedetal(-t1.days, -t1.seconds, -t1.microseconds)和 t1* -1
|
abs(t1)
|
绝对值,等价于: +t 当 t.days >= 0, -t 当 t.days < 0 |
str(t1)
|
返回字符串,格式为: [D day[s], ][H]H:MM:SS[.UUUUUU] |
repr(t1)
|
返回字符串,格式为: datetime.timedelta(D[, S[, U]]) |
total_seconds():返回timedetal的总的秒杀。
5.datetime.tzinfo:与时区有关的相关信息。是一个抽象类,不能被实例化。
如果需要使用时区就必须派生子类,并实现其几个方法。可以尝试使用第三方的包来处理时区,如pytz。
时间格式字符含义:日期段字符表示都是小写(除了%Y),时间段的都是大写
字符符号
|
含义
|
%a
|
星期的英文简写,如Sat |
%A
|
星期的英文全写,如Wednesday
|
%b
|
月份的英文简写,如Jan
|
%B
|
月份的英文全写,如January
|
%c
|
适当语言环境下的日期和时间,如01/18/14 11:14:23
|
%d
|
日,月中的第几日,范围在[1-31]依具体月份决定 |
%f
|
微妙,范围[0-999999]
|
%H
|
小时(24小时制),范围[0-23] |
%I
|
小时(12小时制),范围[0-11]
|
%j
|
日,年中的第几日,范围在[001-356]依具体年份定 |
%m
|
月,范围在[01-12]
|
%M
|
分,范围在[01-59]
|
%p
|
上下午,AM或者PM
|
%S
|
秒,范围[0-61],因为有闰秒等原因所以是61而非59
|
%U
|
周,一年中的第几周,范围[00-53],星期天是周的第一天,所有在新年第一个周日之前的天都算为这新一年的第0周
|
%w
|
天在这周内的天数,范围[0-6],0表示周日
|
%W
|
周,一年中的第几周,范围[00-53],星期一是周的第一天,所有在新年第一个周一之前的天都算为这新一年的第0周
|
%x
|
适当语言环境下的日期,如01/18/14
|
%X
|
适当语言环境下的时间,如11:14:23
|
%y
|
年份后两位,如14 |
%Y
|
年份,如2014
|
%z
|
与utc时间的间隔 (如果是本地时间,返回空字符串) |
%Z
|
时区名称(如果是本地时间,返回空字符串) |
%%
|
%
|
time模块
time模块的实现主要调用C函数的time.h库,所以各个平台可能有所不同
time中表现时间的方式有三种:
1.int型,从1970年1月1号凌晨开始到当前的秒杀,即时间戳。
2.struct_time结构体,以元组的形式表示,共有九个元素,同一个时间戳的struct_time会因为时区不同而不同。
3.格式化字符串,如UTC(通用标准时间)格式时间,中国为UTC+8。
一,time.struct_time
truct_time有如下九个属性,可以用属性名或者索引调用来获得对应的值。
索引(Index)属性(Attribute)值(Values)
0 | tm_year(年) | 比如2011 |
1 | tm_mon(月) | 1 - 12 |
2 | tm_mday(日) | 1 - 31 |
3 | tm_hour(时) | 0 - 23 |
4 | tm_min(分) | 0 - 59 |
5 | tm_sec(秒) | 0 - 61 |
6 | tm_wday(weekday) | 0 - 6(0表示周一) |
7 | tm_yday(一年中的第几天) | 1 - 366 |
8 | tm_isdst(是否是夏令时) | 默认为-1 |
二,time模块方法
2.1 获得时间戳:
time():返回当前的时间戳,自1970至当前的秒数,float类型。
mktime(struct_time):将一个struct_time或九元元组转换成为一个时间戳。
clock():在Windows上,在第一次调用的时候,返回的是程序运行的实际秒数;之后调用表示,从第一次调用到当前调用的间隔秒数;在UNIX系统上,它返回的是“进程时间”,它是用秒表示的浮点数(时间戳)。
2.2 获得struct_time:
localtime([secs]):无参数时返回本时区当前时间的struct_time,如果有参数时间戳secs,就是将此时间戳转换为struct_time。
gmtime([secs]):和localtime()方法类似,无参数时gmtime()是获取0时区的当前时间。如果有参数secs,就是将此时间戳转换为struct_time。
strptime(string[, format]):将string字符串按照format格式进行转换,获得一个struct_time。
2.3 获得字符串
ctime([secs]):无参数时,表示当前时间的字符串;有参数时,把时间戳转换为字符串形式。如:Tue Jan 21 23:07:16 2014
asctime([struct_time]):无参数时,表示当前时间的字符串;有参数时,把一个九元元组或者struct_time转换为字符串形式。
strftime(format[, struct_time]):将一个struct_time或九元元组按format字符串转换为对应时间字符串;如果struct_time未传入则去time.localtime()当前时间。
2.4 其他
sleep(secs):线程推迟指定秒杀。
三,time中三种时间表现的相互转换
![](http://dl2.iteye.com/upload/attachment/0093/7521/57706f13-f7d0-3ef4-a410-405a5d2ea3a7.jpg)
Calendar模块
Calendar是Unix cal命令的实现,可以将给定的年份/月份/日期的日历输出到设备上。
一,属性
周常量:MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
day_name:代表一周内每天的名称数组,如calendar.day_name[0]是Monday。
day_abbr:代表一周内每天名称简写数组,如calendar.day_abbr[0]是Mon。
month_name:代表一年内每月的名称数组,如calendar.month_name[1]是January。
month_abbr:代表一年内每月的简称数组,如calendar.month_abbr[1]是Jan。
二,方法
isleap(year):是否是闰年,是返回True,否返回False。
leapdays(year1, year2):返回year1到year2(不包含在内)之间的闰年书,如calendar.leapdays(2012, 2017)是2。
weekday(year, month, day):返回对应那天是星期几,星期一是从0开始,如weekday(2014, 1, 27)是0。
setfirstweekday(weekday):设置每周的起始是周几。
firstweekday():返回每周的起始是周几。如:先calendar.setfirstweekday(calendar.FRIDAY),则返回4。
weekheader(n):返回一周的星期的简写,n代表简写的长短。如:calendar.weekheader(3)则Fri Sat Sun Mon Tue Wed Thu
monthrange(year,
month):返回第一个元素是指定月份的第一天是周几,第二个元素是指定月份最后一天是几号的元组。如calendar.monthrange(2014,
2)返回是(5, 28),即2014年2月1号是周六,最后一天是2月28号。
month(year, month[, w[, l]])):返回指定月的标准日历字符串
prmonth(year, month[, w[, l]])):直接打印出指定月的标准日历。等价于print calendar.month(year, month)。
calendar(year[, w[, l[c]]]):返回一个指定年的表征日历字符串。
prcal(year[, w[, l[c]]]):打印出一个指定年的表征日历。等价于print calendar.calendar(year)。
timegm(tuple):tuple是一个时间元组,至少六元,返回一个时间戳。
三,类
Calendar([firstweekday]):firstweekday代表每周的起始是周几,一个日历类。
类中的方法:
1. iterweekdays():返回一个iterater,里面包含着周几的七个数字形式,起始数字按firstweekday为准,如果firstweekday设置为calendar.MONDAY,则返回是0 1 2 3 4 5 6。
2. itermonthdates(year, month):返回指定月的日期字符串的一个iterator,必须从每月的firstweekday开始,月末的一整周也包含在内。总共输出是7的倍数个日期。
如:cal2 = calendar.Calendar(calendar.MONDAY)
iter1 = cal2.itermonthdates(2014, 1)
遍历输出:
2013-12-30 到 2014-02-02
3. itermonthdays(year, month) :返回指定月的日期字符串的日部分的一个iterator,必须从每月的firstweekday开始,总共输出是7的倍数个日期,非本月内的日为0填充。
如:cal = calendar.Calendar(calendar.MONDAY)
iter = cal.itermonthdates(2014, 1)
遍历输出:
0 0 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 0 0
4. itermonthdays2(year, month):相比 itermonthdays(year, month) 返回的iterator内的元素是一个二维元组,第一维是和termonthdays(year, month)一样,第二维是对应的星期(周一为0)。
如:cal = calendar.Calendar(calendar.MONDAY)
iter = cal.itermonthdates(2014, 1)
遍历输出:
(0, 0) (0, 1) (1, 2) (2, 3) (3, 4) (4, 5) (5, 6) (6, 0) (7, 1) (8,
2) (9, 3) (10, 4) (11, 5) (12, 6) (13, 0) (14, 1) (15, 2) (16, 3) (17,
4) (18, 5) (19, 6) (20, 0) (21, 1) (22, 2) (23, 3) (24, 4) (25, 5) (26,
6) (27, 0) (28, 1) (29, 2) (30, 3) (31, 4) (0, 5) (0, 6)
TextCalendar([firstweekday]):此类能生成无格式的文本日期。
类中的方法:
1. formatmonth(theyear, themonth[, w[, l]]):返回一个字符串月日历。默认w=0,l=0。w和l分别代表输出日历中的宽度和高度。
2. prmonth(theyear, themonth[, w[, l]]):等同于print formatmonth(theyear, themonth[, w[, l]])。
3. formatyear(theyear[, w[, l[, c[, m]]]]):返回一个字符串年日历。w,l,c,m表示列宽,行高, 每个月间的宽度, 每行显示的月数。
4. pryear(theyear[, w[, l[, c[, m]]]]):等同于print formatyear(theyear[, w[, l[, c[, m]]]])。
HTMLCalendar([firstweekday]):firstweekday代表每周的起始是周几,一个用html表格代表的日历类。
类中的方法:
1. formatmonth(theyear, themonth[, withyear]):返回一个html中的table,表示指定theyear年中的themonth月的日志字符串。
2. formatyear(theyear[, width]):同上,返回指定theyear年的日历字符串。
3. formatyearpage(theyear[, width[, css[, encoding]]]):返回完整的一个页面的html,年的日历。