Python模块学习笔记— —time与datatime

Python提供了多个内置模块用于操作日期时间。像calendar,time,datetime。首先对time模块中最经常使用的几个函数作一个介绍,它提供的接口与C标准库time.h基本一致。然后再介绍一下datatime模块,相比于time模块,datetime模块的接口则更直观、更easy调用。

time模块

time.time
time.time()函数返回从1970年1月1日以来的秒数,这是一个浮点数。

import time
print time.time()

01

time.sleep
能够通过调用time.sleep来挂起当前的进程。time.sleep接收一个浮点型參数,參数单位为秒。表示进程挂起的时间。

time.clock
在windows操作系统上,time.clock() 返回第一次调用该方法到如今的秒数,其准确度高于1微秒。能够使用该函数来记录程序运行的时间。

import time
print time.clock()
time.sleep(2)
print time.clock()
time.sleep(3)
print time.clock()

02

time.gmtime
该函数原型为:time.gmtime([sec]),可选的參数sec表示从1970-1-1以来的秒数。

其默认值为time.time(),函数返回time.struct_time类型的对象(struct_time是在time模块中定义的表示时间的对象)。

import time
print time.gmtime()  
print time.gmtime(time.time() - 24 * 60 * 60) 

03

time.localtime
time.localtime与time.gmtime非常相似,也返回一个struct_time对象,能够把它看作是gmtime()的本地化版本号。

time.mktime
time.mktime运行与gmtime(), localtime()相反的操作。它接收struct_time对象作为參数。返回用秒数来表示时间的浮点数。

import time
print time.mktime(time.localtime())
print time.time()

04

time.strftime
time.strftime将日期转换为字符串表示。它的函数原型为:time.strftime(format[, t])。參数format是格式字符串(格式字符串的知识能够參考:time.strftime)。可选的參数t是一个struct_time对象。

import time
print time.strftime('%Y-%m-%d %H:%M:%S', time.gmtime())
print time.strftime('Weekday: %w; Day of the yesr: %j')

05

time.strptime
按指定格式解析一个表示时间的字符串,返回struct_time对象。

该函数原型为:time.strptime(string, format),两个參数都是字符串。

import time
print time.strptime('201-06-23 15:30:53', '%Y-%m-%d %H:%M:%S')

06

以上不过time模块中最经常使用的几个方法,还有非常多其它的方法如:time.timezone, time.tzname …感兴趣的童鞋能够參考Python手冊 time 模块

datetime模块

datetime模块定义了两个常量:datetime.MINYEAR和datetime.MAXYEAR,分别表示datetime所能表示的最小、最大年份。

当中。MINYEAR = 1,MAXYEAR = 9999。

datetime模块定义了以下这几个类:
-datetime.date:表示日期的类。经常使用的属性有year, month, day。
-datetime.time:表示时间的类。经常使用的属性有hour, minute, second, microsecond;
-datetime.datetime:表示日期时间。
-datetime.timedelta:表示时间间隔。即两个时间点之间的长度。
-datetime.tzinfo:与时区有关的相关信息。(这里不具体充分讨论该类。感兴趣的童鞋能够參考python手冊)
【注】上面这些类型的对象都是不可变(immutable)的。

date类

date类表示一个日期。其构造函数例如以下:
class datetime.date(year, month, day)
year的范围是[MINYEAR, MAXYEAR],即[1, 9999];
month的范围是[1, 12]。
day的最大值依据给定的year, month參数来决定,闰年2月份有29天。

date类定义了一些经常使用的类方法与类属性。方便我们操作:
-date.max、date.min:date对象所能表示的最大、最小日期;
-date.resolution:date对象表示日期的最小单位。

这里是天。
-date.today():返回一个表示当前本地日期的date对象;
-date.fromtimestamp(timestamp):依据给定的时间戮。返回一个date对象。
-datetime.fromordinal(ordinal):将Gregorian日历时间转换为date对象;(Gregorian Calendar:一种日历表示方法,相似于我国的农历,西方国家使用比較多。)

from datetime import * 
import time  
print 'date.max:', date.max 
print 'date.min:', date.min 
print 'date.today():', date.today() 
print 'date.fromtimestamp():', date.fromtimestamp(time.time())

07

date提供的实例方法和属性:
-date.year、date.month、date.day:年、月、日;
-date.replace(year, month, day):生成一个新的日期对象,用參数指定的年,月,日取代原有对象中的属性。


-date.timetuple():返回日期相应的time.struct_time对象;
-date.toordinal():返回日期相应的Gregorian Calendar日期;
-date.weekday():返回weekday。假设是星期一,返回0。假设是星期2,返回1,以此类推;
-data.isoweekday():返回weekday,假设是星期一,返回1;假设是星期2,返回2,以此类推。
-date.isocalendar():返回格式如(year,month。day)的元组。
-date.isoformat():返回格式如’YYYY-MM-DD’的字符串;
-date.strftime(fmt):自己定义格式化字符串。

from datetime import * 
now = date(2015,6,10)
tomorrow = now.replace(day = 11)
print 'now:',now, ', tomorrow:',tomorrow
print 'timetuple():', now.timetuple()
print 'weekday():', now.weekday()
print 'isoweekday():', now.isoweekday()
print 'isocalendar():', now.isocalendar()
print 'isoformat():', now.isoformat()

08

date还对一些操作进行了重载,同意对日期进行例如以下一些操作:
-date2 = date1 + timedelta # 日期加上一个间隔,返回一个新的日期对象(timedelta将在以下介绍,表示时间间隔)
-date2 = date1 - timedelta # 日期隔去间隔,返回一个新的日期对象
-timedelta = date1 - date2 # 两个日期相减。返回一个时间间隔对象
date1 < date2 # 两个日期进行比較
【注】对日期进行操作时。要防止日期超出它所能表示的范围。

from datetime import * 
now = date.today()
tomorrow = now.replace(day = 11)
delta = tomorrow - now
print 'now:', now, ' tomorrow:', tomorrow
print 'timedelta:', delta
print now + delta
print tomorrow > now

09

time类

time类表示时间,由时、分、秒以及微秒组成。

time类的构造函数例如以下:
class datetime.time(hour[, minute[, second[, microsecond[, tzinfo]]]])
參数tzinfo表示时区信息。各參数的取值范围:hour的范围为[0, 24),minute的范围为[0, 60),second的范围为[0, 60)。microsecond的范围为[0, 1000000)。

time类定义的类属性:
-time.min、time.max:time类所能表示的最小、最大时间。当中time.min = time(0, 0, 0, 0)。 time.max = time(23, 59, 59, 999999);
-time.resolution:时间的最小单位。这里是1微秒;

time类提供的实例方法和属性:
-time.hour、time.minute、time.second、time.microsecond:时、分、秒、微秒。
-time.tzinfo:时区信息。
-time.replace([hour[, minute[, second[, microsecond[, tzinfo]]]]]):创建一个新的时间对象,用參数指定的时、分、秒、微秒取代原有对象中的属性(原有对象仍保持不变);
-time.isoformat():返回型如”HH:MM:SS”格式的字符串表示。
-time.strftime(fmt):返回自己定义格式化字符串。

from datetime import * 
tm = time(7, 17, 10) 
print 'tm:', tm 
print 'hour: %d, minute: %d, second: %d, microsecond: %d' 
      % (tm.hour, tm.minute, tm.second, tm.microsecond)
tm1 = tm.replace(hour = 8) 
print 'tm1:', tm1 
print 'isoformat():', tm.isoformat()

10

像date一样,time也能够对两个time对象进行比較,或者相减返回一个时间间隔对象。

datetime类

datetime是date与time的结合体。包含date与time的全部信息。它的构造函数例如以下:
datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])
各參数的含义与date、time的构造函数中的一样,要注意參数值的范围。

datetime类定义的类属性与方法:
-datetime.min、datetime.max:datetime所能表示的最小值与最大值;
-datetime.resolution:datetime最小单位;
-datetime.today():返回一个表示当前本地时间的datetime对象;
-datetime.now([tz]):返回一个表示当前本地时间的datetime对象,假设提供了參数tz,则获取tz參数所指时区的本地时间。
-datetime.utcnow():返回一个当前utc时间的datetime对象。
-datetime.fromtimestamp(timestamp[, tz]):依据时间戮创建一个datetime对象。參数tz指定时区信息。
-datetime.utcfromtimestamp(timestamp):依据时间戮创建一个datetime对象;
-datetime.combine(date, time):依据date和time,创建一个datetime对象;
-datetime.strptime(date_string, format):将格式字符串转换为datetime对象;

from datetime import * 
import time
print 'datetime.max:', datetime.max 
print 'datetime.min:', datetime.min 
print 'datetime.resolution:', datetime.resolution 
print 'today():', datetime.today() 
print 'now():', datetime.now() 
print 'utcnow():', datetime.utcnow() 
print 'fromtimestamp(tmstmp):', datetime.fromtimestamp(time.time()) 
print 'utcfromtimestamp(tmstmp):', datetime.utcfromtimestamp(time.time())

11

datetime类提供的实例方法与属性(非常多属性或方法在date和time中已经出现过,可參考上文):
-datetime.year、month、day、hour、minute、second、microsecond、tzinfo:
-datetime.date():获取date对象;
-datetime.time():获取time对象。
-datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]):
-datetime.timetuple()
-datetime.utctimetuple()
-datetime.toordinal()
-datetime.weekday()
-datetime.isocalendar()
-datetime.isoformat([sep])
-datetime.ctime():返回一个日期时间的C格式字符串。等效于time.ctime(time.mktime(dt.timetuple()));
datetime.strftime(format)
像date一样。也能够对两个datetime对象进行比較,或者相减返回一个时间间隔对象。或者日期时间加上一个间隔返回一个新的日期时间对象。

格式字符串
datetime、date、time都提供了strftime()方法,该方法接收一个格式字符串。输出日期时间的字符串表示。

格式字符 意义
%a 星期的简写,如星期三为Web
%A 星期的全写,如星期三为Wednesday
%b 月份的简写,如4月份为Apr
%B 月份的全写,如4月份为April
%c 日期时间的字符串表示。(如: 04/07/10 10:43:39)
%d 日在这个月中的天数(是这个月的第几天)
%f 微秒(范围[0,999999])
%H 小时(24小时制。[0, 23])
%I 小时(12小时制,[0, 11])
%j 日在年中的天数 [001,366](是当年的第几天)
%m 月份([01,12])
%M 分钟([00,59])
%p AM或者PM
%S 秒(范围为[00,61])
%U 周在当年的周数当年的第几周),星期天作为周的第一天
%w 今天在这周的天数。范围为[0, 6],6表示星期天
%W 周在当年的周数(是当年的第几周),星期一作为周的第一天
%x 日期字符串(如:04/07/10)
%X 时间字符串(如:10:43:39)
%y 2个数字表示的年份
%Y 4个数字表示的年份
%z 与utc时间的间隔 (假设是本地时间,返回空字符串)
%Z 时区名称(假设是本地时间。返回空字符串)
%% %% => %
from datetime import * 
import time
dt = datetime.now() 
print '(%Y-%m-%d %H:%M:%S %f): ', dt.strftime('%Y-%m-%d %H:%M:%S %f') 
print '(%Y-%m-%d %H:%M:%S %p): ', dt.strftime('%y-%m-%d %I:%M:%S %p') 
print '%%a: %s ' % dt.strftime('%a') 
print '%%A: %s ' % dt.strftime('%A') 
print '%%b: %s ' % dt.strftime('%b') 
print '%%B: %s ' % dt.strftime('%B') 
print '日期时间%%c: %s ' % dt.strftime('%c') 
print '日期%%x:%s ' % dt.strftime('%x') 
print '时间%%X:%s ' % dt.strftime('%X') 
print '今天是这周的第%s天 ' % dt.strftime('%w') 
print '今天是今年的第%s天 ' % dt.strftime('%j') 
print '今周是今年的第%s周 ' % dt.strftime('%U')

12

原文地址:https://www.cnblogs.com/lcchuguo/p/5241215.html