python中的datetime模块

来源:互联网 发布:php集成开发环境 编辑:程序博客网 时间:2024/05/24 05:02
文章转自:http://www.cnblogs.com/tkqasn/p/6001134.html


datetime模块

datatime模块重新封装了time模块,提供更多接口,提供的类有:date,time,datetime,timedelta,tzinfo。

1、date类

datetime.date(year, month, day)

静态方法和字段

date.max、date.min:date对象所能表示的最大、最小日期;date.resolution:date对象表示日期的最小单位。这里是天。date.today():返回一个表示当前本地日期的date对象;date.fromtimestamp(timestamp):根据给定的时间戮,返回一个date对象;
复制代码
from datetime import *import timeprint   'date.max:', date.maxprint   'date.min:', date.minprint   'date.today():', date.today()print   'date.fromtimestamp():', date.fromtimestamp(time.time())#Output======================# date.max: 9999-12-31# date.min: 0001-01-01# date.today(): 2016-10-26# date.fromtimestamp(): 2016-10-26
复制代码

 

方法和属性

复制代码
d1 = date(2011,06,03)#date对象d1.year、date.month、date.day:年、月、日;d1.replace(year, month, day):生成一个新的日期对象,用参数指定的年,月,日代替原有对象中的属性。(原有对象仍保持不变)d1.timetuple():返回日期对应的time.struct_time对象;d1.weekday():返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推;d1.isoweekday():返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;d1.isocalendar():返回格式如(year,month,day)的元组;d1.isoformat():返回格式如'YYYY-MM-DD’的字符串;d1.strftime(fmt):和time模块format相同。
复制代码
复制代码
from datetime import *now = date(2016, 10, 26)tomorrow = now.replace(day = 27)print 'now:', now, ', tomorrow:', tomorrowprint 'timetuple():', now.timetuple()print 'weekday():', now.weekday()print 'isoweekday():', now.isoweekday()print 'isocalendar():', now.isocalendar()print 'isoformat():', now.isoformat()print 'strftime():', now.strftime("%Y-%m-%d")#Output========================# now: 2016-10-26 , tomorrow: 2016-10-27# timetuple(): time.struct_time(tm_year=2016, tm_mon=10, tm_mday=26, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=300, tm_isdst=-1)# weekday(): 2# isoweekday(): 3# isocalendar(): (2016, 43, 3)# isoformat(): 2016-10-26# strftime(): 2016-10-26
复制代码

 

2、time类

datetime.time(hour[ , minute[ , second[ , microsecond[ , tzinfo] ) 

静态方法和字段

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

 

方法和属性

复制代码
t1 = datetime.time(10,23,15)#time对象t1.hour、t1.minute、t1.second、t1.microsecond:时、分、秒、微秒;t1.tzinfo:时区信息;t1.replace([ hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ):创建一个新的时间对象,用参数指定的时、分、秒、微秒代替原有对象中的属性(原有对象仍保持不变);t1.isoformat():返回型如"HH:MM:SS"格式的字符串表示;t1.strftime(fmt):同time模块中的format;
复制代码
复制代码
from  datetime import *tm = time(23, 46, 10)print   'tm:', tmprint   'hour: %d, minute: %d, second: %d, microsecond: %d' % (tm.hour, tm.minute, tm.second, tm.microsecond)tm1 = tm.replace(hour=20)print   'tm1:', tm1print   'isoformat():', tm.isoformat()print   'strftime()', tm.strftime("%X")#Output==============================================# tm: 23:46:10# hour: 23, minute: 46, second: 10, microsecond: 0# tm1: 20:46:10# isoformat(): 23:46:10# strftime() 23:46:10
复制代码

3、datetime类

datetime相当于date和time结合起来。
datetime.datetime (year, month, day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] )

静态方法和字段

复制代码
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 timeprint   'datetime.max:', datetime.maxprint   'datetime.min:', datetime.minprint   'datetime.resolution:', datetime.resolutionprint   '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())#output======================# datetime.max: 9999-12-31 23:59:59.999999# datetime.min: 0001-01-01 00:00:00# datetime.resolution: 0:00:00.000001# today(): 2016-10-26 23:12:51.307000# now(): 2016-10-26 23:12:51.307000# utcnow(): 2016-10-26 15:12:51.307000# fromtimestamp(tmstmp): 2016-10-26 23:12:51.307000# utcfromtimestamp(tmstmp): 2016-10-26 15:12:51.307000
复制代码

 

方法和属性

复制代码
dt=datetime.now()#datetime对象dt.year、month、day、hour、minute、second、microsecond、tzinfo:dt.date():获取date对象;dt.time():获取time对象;dt. replace ([ year[ , month[ , day[ , hour[ , minute[ , second[ , microsecond[ , tzinfo] ] ] ] ] ] ] ]):dt. timetuple ()dt. utctimetuple ()dt. toordinal ()dt. weekday ()dt. isocalendar ()dt. isoformat ([ sep] )dt. ctime ():返回一个日期时间的C格式字符串,等效于time.ctime(time.mktime(dt.timetuple()));dt. strftime (format)
复制代码

4.timedelta类,时间加减

使用timedelta可以很方便的在日期上做天days,小时hour,分钟,秒,毫秒,微妙的时间计算,如果要计算月份则需要另外的办法。

复制代码
#coding:utf-8from  datetime import *dt = datetime.now()#日期减一天dt1 = dt + timedelta(days=-1)#昨天dt2 = dt - timedelta(days=1)#昨天dt3 = dt + timedelta(days=1)#明天delta_obj = dt3-dtprint type(delta_obj),delta_obj#<type 'datetime.timedelta'> 1 day, 0:00:00print delta_obj.days ,delta_obj.total_seconds()#1 86400.0
复制代码

 5、tzinfo时区类

复制代码
#! /usr/bin/python# coding=utf-8from datetime import datetime, tzinfo,timedelta"""tzinfo是关于时区信息的类tzinfo是一个抽象类,所以不能直接被实例化"""class UTC(tzinfo):    """UTC"""    def __init__(self,offset = 0):        self._offset = offset    def utcoffset(self, dt):        return timedelta(hours=self._offset)    def tzname(self, dt):        return "UTC +%s" % self._offset    def dst(self, dt):        return timedelta(hours=self._offset)#北京时间beijing = datetime(2011,11,11,0,0,0,tzinfo = UTC(8))print "beijing time:",beijing#曼谷时间bangkok = datetime(2011,11,11,0,0,0,tzinfo = UTC(7))print "bangkok time",bangkok#北京时间转成曼谷时间print "beijing-time to bangkok-time:",beijing.astimezone(UTC(7))#计算时间差时也会考虑时区的问题timespan = beijing - bangkokprint "时差:",timespan#Output==================# beijing time: 2011-11-11 00:00:00+08:00# bangkok time 2011-11-11 00:00:00+07:00# beijing-time to bangkok-time: 2011-11-10 23:00:00+07:00# 时差: -1 day, 23:00:00
原创粉丝点击