python3关于date和time的标准库

python3中关于日期和时间的标准库datetime和time,之前都是用的时候随用随查,今天系统的看一下用这两个库可以做些什么。


1、time标准库

#首先添加一个time对象,看一下该对象的属性和方法
>>> import time,datetime
>>> a = time
>>> type(a)
<class 'module'>
>>> dir(a)
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'clock', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'perf_counter', 'process_time', 'sleep', 'strftime', 'strptime', 'struct_time', 'time', 'timezone', 'tzname']

使用help(time)查看一下帮助文件,里面有对应方法的说明(英语好是多么重要,我还得翻译)

Variables:

timezone -- difference in seconds between UTC and local standard time
altzone -- difference in  seconds between UTC and local DST time
daylight -- whether local time should reflect DST
tzname -- tuple of (standard time zone name, DST time zone name)

Functions:

time() -- return current time in seconds since the Epoch as a float    返回当前时间的时间戳格式(浮点型)
clock() -- return CPU time since process start as a float    返回进程启动以来的cpu时间(浮点型)
sleep() -- delay for a number of seconds given as a float    休眠时间
gmtime() -- convert seconds since Epoch to UTC tuple    将一个时间戳类型转化为time tuple,不加参数就是当前时间
localtime() -- convert seconds since Epoch to local time tuple    当前时间的time tuple
asctime() -- convert time tuple to string    time tuple转化成str型
ctime() -- convert time in seconds to string    将秒数转化为str型(是这么理解么?)
mktime() -- convert local time tuple to seconds since Epoch    将time tuple转化为时间戳
strftime() -- convert time tuple to string according to format specification    将time tuple按格式转化为str型
strptime() -- parse string to time tuple according to format specification    将str型按格式转化为time tuple
tzset() -- change the local timezone    更改本地时间

上面4个参数基本不怎么用,主要就是下面这些方法会用到

>>> a.time()
1492154597.892713
>>> a.clock()
1.28294687766011e-06
>>> a.sleep(0.001)
>>> time.gmtime(a.time())
time.struct_time(tm_year=2017, tm_mon=4, tm_mday=14, tm_hour=7, tm_min=24, tm_sec=6, tm_wday=4, tm_yday=104, tm_isdst=0)
>>> time.localtime()
time.struct_time(tm_year=2017, tm_mon=4, tm_mday=14, tm_hour=15, tm_min=24, tm_sec=14, tm_wday=4, tm_yday=104, tm_isdst=0)
>>> time.asctime(time.localtime())
'Fri Apr 14 15:24:31 2017'
>>> time.ctime(time.time())
'Fri Apr 14 15:24:46 2017'
>>> time.mktime(time.localtime())
1492155003.0

再来看strptime和strftime,因为这个涉及到格式,所以要说一下time tuple中的格式
帮助文件中也对格式做了说明,不过帮助文档中并不全面,我在其他人的博客中找到了更全的

%a	本地(locale)简化星期名称
%A	本地完整星期名称
%b	本地简化月份名称
%B	本地完整月份名称
%c	本地相应的日期和时间表示
%d	一个月中的第几天(01 - 31)
%H	一天中的第几个小时(24小时制,00 - 23)
%I	第几个小时(12小时制,01 - 12)
%j	一年中的第几天(001 - 366)
%m	月份(01 - 12)
%M	分钟数(00 - 59)
%p	本地am或者pm的相应符
%S	秒(01 - 61)
%U	一年中的星期数。(00 - 53星期天是一个星期的开始。)第一个星期天之前的所有天数都放在第0周。
%w	一个星期中的第几天(0 - 6,0是星期天)
%W	和%U基本相同,不同的是%W以星期一为一个星期的开始。
%x	本地相应日期
%X	本地相应时间
%y	去掉世纪的年份(00 - 99)
%Y	完整的年份
%Z	时区的名字(如果不存在为空字符)
%%	‘%’字符

知道了格式,strptime和strftime的用法了

>>> time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
'2017-04-14 15:50:10'
>>> time.strptime('2017-04-14 15:50:10','%Y-%m-%d %H:%M:%S')
time.struct_time(tm_year=2017, tm_mon=4, tm_mday=14, tm_hour=15, tm_min=50, tm_sec=10, tm_wday=4, tm_yday=104, tm_isdst=-1)

2、datetime标准库

>>> import datetime
>>> a = datetime
>>> dir(a)
['MAXYEAR', 'MINYEAR', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_divide_and_round', 'date', 'datetime', 'datetime_CAPI', 'time', 'timedelta', 'timezone', 'tzinfo']
>>> dir(a.date)
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'ctime', 'day', 'fromordinal', 'fromtimestamp', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'min', 'month', 'replace', 'resolution', 'strftime', 'timetuple', 'today', 'toordinal', 'weekday', 'year']
>>> dir(a.datetime)
['__add__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__radd__', '__reduce__', '__reduce_ex__', '__repr__', '__rsub__', '__setattr__', '__sizeof__', '__str__', '__sub__', '__subclasshook__', 'astimezone', 'combine', 'ctime', 'date', 'day', 'dst', 'fold', 'fromordinal', 'fromtimestamp', 'hour', 'isocalendar', 'isoformat', 'isoweekday', 'max', 'microsecond', 'min', 'minute', 'month', 'now', 'replace', 'resolution', 'second', 'strftime', 'strptime', 'time', 'timestamp', 'timetuple', 'timetz', 'today', 'toordinal', 'tzinfo', 'tzname', 'utcfromtimestamp', 'utcnow', 'utcoffset', 'utctimetuple', 'weekday', 'year']
>>> dir(a.time)
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'dst', 'fold', 'hour', 'isoformat', 'max', 'microsecond', 'min', 'minute', 'replace', 'resolution', 'second', 'strftime', 'tzinfo', 'tzname', 'utcoffset']

其实主要就是用的者三个包,而且里面有很多方法都是重复的

>>> a = date(1988,4,29)
>>> a.ctime()
'Fri Apr 29 00:00:00 1988'
>>> a.day
29
>>> a.month
4
>>> a.year
1988
>>> a.toordinal()		当前日期距离耶稣生日(- -!公元元年)的天数
725856
>>> b = a.replace(2017,4,14)	返回一个新对象,替换原对象的时间(不改变原有对象的属性)
>>> b
datetime.date(2017, 4, 14)
>>> b.strftime('%Y!%m!%d')		按格式将date格式转化为str
'2017!04!14'
>>> a.timetuple()		将date转化为time tuple
time.struct_time(tm_year=1988, tm_mon=4, tm_mday=29, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=4, tm_yday=120, tm_isdst=-1
>>> date(1988, 4, 29).isocalendar()		Return a 3-tuple containing ISO year, week number, and weekday.(不太理解)
(1988, 17, 5)
>>> (1988, 4, 29).isoformat()	Return string in ISO 8601 format, YYYY-MM-DD
'1988-04-29'
>>> date(2017,4,14).isoweekday()	返回日期的周数(mon==1,sun==7)
5
>>> date.fromordinal(1988)	将一个int型天数转化为对应的年、月、日数信息
datetime.date(6, 6, 11)
>>> date.fromordinal(365)
datetime.date(1, 12, 31)
>>> date.fromordinal(366)
datetime.date(2, 1, 1)
>>> date.fromtimestamp(time.time())	将一个时间戳格式转化为date格式
datetime.date(2017, 4, 14)
>>> date.max	最大的日期数
datetime.date(9999, 12, 31)
>>> date.min	最小的日期数
datetime.date(1, 1, 1)
>>> date.today()
datetime.date(2017, 4, 14)	当前日期date格式
>>> date.resolution    date的最小单位
datetime.timedelta(1)

time与datetime其实大同小异,只是有个别方法不同

posted on 2017-04-14 16:21  胡欣欣  阅读(1022)  评论(0编辑  收藏  举报