IT博客汇
  • 首页
  • 精华
  • 技术
  • 设计
  • 资讯
  • 扯淡
  • 权利声明
  • 登录 注册

    [原]5.1.4 datetime对象

    caimouse发表于 2015-11-22 09:00:44
    love 0

    类datetime创建的对象包括了日期和时间相关信息。

    class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

    构造一个datetime对象,需要输入年、月、日三个参数,其它参数都是可选。输入的参数应满足下面的范围:

    l MINYEAR <= year <= MAXYEAR

    l 1 <= month <= 12

    l 1 <= day <= 小于指定月份的天数

    l 0 <= hour < 24

    l 0 <= minute < 60

    l 0 <= second < 60

    l 0 <= microsecond < 1000000

    如果输入的值超出范围,就会抛出异常ValueError。

     

    classmethod datetime.today() 

    从当前时间构造一个datetime对象,返回当前日期和时间,但tzinfo设置为None。相当于datetime.fromtimestamp(time.time())。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    print('to:', to)

    结果输出如下:

    to: 2015-11-04 09:45:54.856671

     

    classmethod datetime.now(tz=None) 

    返回当前日期和时间的datetime对象。如果参数tz没有指定,它相当于today()函数的功能。如果指定tz为tzinfo对象时区,就会把当前日期和时间转换为对应时区的日期和时间。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.now()

    print('to:', to)

    结果输出如下:

    to: 2015-11-04 14:05:16.029719

     

    classmethod datetime.utcnow() 

    返回UTC的日期和时间,时区tzinfo为None。相当于datetime.now(timezone.utc)。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.now(datetime.timezone.utc)

    utc = datetime.datetime.utcnow()

    print('to:', to)

    print('utc:', utc)

    结果输出如下:

    to: 2015-11-05 01:37:55.466599+00:00

    utc: 2015-11-05 01:37:55.466599

     

    classmethod datetime.fromtimestamp(timestamp, tz=None) 

    从一个POSIX的时间字符串构造日期和时间对象返回,比如从time.time()。如果tz为None,从本地时区作转换,如果指定时区就根据指定时区来转换时间。如果超出了范围,就会抛出异常OverflowError。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.fromtimestamp(10000)

    print('to:', to)

    结果输出如下:

    to: 1970-01-01 10:46:40

     

    classmethod datetime.utcfromtimestamp(timestamp) 

    返回UTC的POSIX的日期和时间,并且tzinfo设置为None。相当于:

    datetime(1970, 1, 1) + timedelta(seconds=timestamp)

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.fromtimestamp(10000)

    utc = datetime.datetime.utcfromtimestamp(10000)

    print('to:', to)

    print('utc:', utc)

    结果输出如下:

    to: 1970-01-01 10:46:40

    utc: 1970-01-01 02:46:40

     

    classmethod datetime.fromordinal(ordinal) 

    从天序数来生成日期,0年1月1日作为第1天。如果超出表示范围抛出异常ValueError。默认时、分、秒和微秒都是0, 时区tzinfo设置为None。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.fromordinal(10000)

    print('to:', to)

    结果输出如下:

    to: 0028-05-18 00:00:00

     

    classmethod datetime.combine(date, time) 

    组合date和time对象为一个datetime对象,日期使用date对象,时间使用time对象,时区也是使用time对象。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    to = datetime.datetime.combine(to.date(), to.timetz())

    print('to:', to)

    结果输出如下:

    to: 2015-11-06 08:39:43.202053

     

    classmethod datetime.strptime(date_string, format) 

    根据格式format来分析时间字符串date_string,然后生成一个datetime对象返回。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    strTime = to.strftime("%A %d. %B %Y")

    to = datetime.datetime.strptime(strTime, "%A %d. %B %Y")

    print('to:', to)

    结果输出如下:

    to: 2015-11-06 00:00:00

     

    datetime的类型属性:

    datetime.min 

    表示最小的日期时间,datetime(MINYEAR, 1, 1, tzinfo=None)。

     

    datetime.max 

    表示最大的日期时间datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, tzinfo=None)。

     

    datetime.resolution 

    表示两个日期时间对象之间最小差值,timedelta(microseconds=1)。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    print('min:', to.min)

    print('max:', to.max)

    print('resolution:', to.resolution)

    结果输出如下:

    min: 0001-01-01 00:00:00

    max: 9999-12-31 23:59:59.999999

    resolution: 0:00:00.000001

     

    datetime类实例属性:

    datetime.year 

    表示范围在MINYEAR和MAXYEAR之间。

     

    datetime.month 

    表示范围在1和12之间。

     

    datetime.day 

    表示范围在1和给出年的月份总天数之间。

     

    datetime.hour 

    表示24小时。

     

    datetime.minute 

    表示范围60。

     

    datetime.second 

    表示范围60。

     

    datetime.microsecond 

    表示范围为1000000。

     

    datetime.tzinfo 

    表示时间区。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    print('year:', to.year)

    print('month:', to.month)

    print('day:', to.day)

    print('hour:', to.hour)

    print('minute:', to.minute)

    print('second:', to.second)

    print('microsecond:', to.microsecond)

    print('tzinfo:', to.tzinfo)

    结果输出如下:

    year: 2015

    month: 11

    day: 6

    hour: 9

    minute: 54

    second: 28

    microsecond: 146576

    tzinfo: None

     

    datetime对象支持操作:

    日期时间对象与时间变量相加datetime2 = datetime1 + timedelta

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    td = datetime.timedelta(10)

    print('to:', to)

    to = to + td

    print('to+td:', to)

    结果输出如下:

    to: 2015-11-06 10:21:16.326559

    to+td: 2015-11-16 10:21:16.326559

     

    日期时间对象与时间变量相减datetime2 = datetime1 - timedelta

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    td = datetime.timedelta(10)

    print('to:', to)

    to = to - td

    print('to-td:', to)

    结果输出如下:

    to: 2015-11-09 14:17:47.119363

    to-td: 2015-10-30 14:17:47.119363

     

    两个日期时间相减得到时间差值timedelta = datetime1 - datetime2

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    dt = datetime.datetime(2015, 11, 11)

    print('to:', to)

    td = to - dt

    print('to-td:', td)

    结果输出如下:

    to: 2015-11-12 08:31:33.137212

    to-td: 1 day, 8:31:33.137212

     

    日期时间对象进行比较datetime1 < datetime2

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    dt = datetime.datetime(2015, 11, 11)

    print('to:', to)

    print('to > dt:', to > dt)

    结果输出如下:

    to: 2015-11-12 11:03:44.813513

    to > dt: True

     

    datetime实例拥有方法:

    datetime.date() 

    返回date对象表示年、月和日。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

     

    print('to.date():', to.date())

    结果输出如下:

    to.date(): 2015-11-12

     

    datetime.time() 

    返回time对象,表示同样的时、分、秒和微秒。tzinfo为None。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    print('to.time():', to.time())

    结果输出如下:

    to.time(): 11:31:57.696341

     

    datetime.timetz() 

    返回time对象,表示同样的时、分、秒和微秒,也包括tzinfo属性。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    print('to.timetz():', to.timetz())

    结果输出如下:

    to.timetz(): 11:39:20.299655

     

    datetime.replace([year[, month[, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]]]]]) 

    返回一个datetime对象,除了输入相应参数的值修改之外,其它值与实例对象相同。

    例子:

    #python 3.4.3

    import datetime

     

    to = datetime.datetime.today()

    new = to.replace(year = 2014)

    print('to:', to)

    print('new:', new)

    结果输出如下:

    to: 2015-11-12 11:42:49.940646

    new: 2014-11-12 11:42:49.940646

     

    datetime.astimezone(tz=None) 

    返回一个指定的时区变换的datetime对象。

    例子:

    #python 3.4.3

    import datetime

    from pytz import timezone

     

    la = timezone('America/Los_Angeles')

    dt = la.localize(datetime.datetime(2015, 11, 11, 1, 2, 3))

    fmt = '%Y-%m-%d %H:%M:%S %Z (%z)'

    gmt = timezone('GMT')

    gmt.normalize(dt).strftime(fmt)

    new = dt.astimezone()

    print('new:', new)

    结果输出如下:

    new: 2015-11-12 01:02:03+16:00

     

    datetime.utcoffset() 

    如果tzinfo是None返回None;否则返回self.tzinfo.utcoffset(self)。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.today()

    new = dt.utcoffset()

    print('new:', new)

    结果输出如下:

    new: None

     

    datetime.dst() 

    如果tzinfo是None,返回None;如果非空则返回self.tzinfo.dst(self)。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.today()

    new = dt.dst()

    print('new:', new)

    结果输出如下:

    new: None

     

    datetime.tzname() 

    如果tzinfo是None,否则返回self.tzinfo.tzname(self)。

    例子如下:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.now(datetime.timezone.utc)

    new = dt.tzname()

    print('new:', new)

    结果输出如下:

    new: UTC+00:00

     

    datetime.timetuple() 

    返回一个time.struct_time对象,与time.localtime()相同。d.timetuple()与time.struct_time((d.year, d.month, d.day, d.hour, d.minute, d.second, d.weekday(), yday, dst))相同。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.now(datetime.timezone.utc)

    new = dt.timetuple()

    print('new:', new)

    结果输出如下:

    new: time.struct_time(tm_year=2015, tm_mon=11, tm_mday=16, tm_hour=1, tm_min=26, tm_sec=55, tm_wday=0, tm_yday=320, tm_isdst=-1)

     

    datetime.utctimetuple()  

    如果对象非UTC时间,就会格式化为UTC时间,再返回time.struct_time对象。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.now(datetime.timezone.utc)

    new = dt.timetuple()

    print('new:', new)

    utc = dt.utctimetuple()

    print('utc:', utc)

    结果输出如下:

    new: time.struct_time(tm_year=2015, tm_mon=11, tm_mday=16, tm_hour=1, tm_min=34, tm_sec=42, tm_wday=0, tm_yday=320, tm_isdst=-1)

    utc: time.struct_time(tm_year=2015, tm_mon=11, tm_mday=16, tm_hour=1, tm_min=34, tm_sec=42, tm_wday=0, tm_yday=320, tm_isdst=0)

     

    datetime.toordinal() 

    返回公历的开始的计算的天数。等同self.date().toordinal()。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.now(datetime.timezone.utc)

    to = dt.toordinal()

    print('to:', to)

    结果输出如下:

    to: 735918

     

    datetime.timestamp() 

    返回POSIX标准的时间,使用浮点数来表示已经经历多少秒。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.now(datetime.timezone.utc)

    to = dt.timestamp()

    print('to:', to)

    结果输出如下:

    to: 1447638918.534684

     

    datetime.weekday() 

    返回日期时间是一周里第几天,0表示周一,6表示是周日。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.now(datetime.timezone.utc)

    to = dt.weekday()

    print('to:', to)

    结果输出如下:

    to: 0

     

    datetime.isoweekday() 

    返回日期是一周里第几天,采用ISO标准表示,1是表示周一,7是表示周日。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.now(datetime.timezone.utc)

    to = dt.isoweekday()

    print('to:', to)

    结果输出如下:

    to: 1

     

    datetime.isocalendar() 

    返回三个元素(ISO标准的年,ISO标准的第几周,ISO标准的一周第几天)。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.now(datetime.timezone.utc)

    to = dt.isocalendar()

    print('to:', to)

    结果输出如下:

    to: (2015, 47, 1)

     

    datetime.isoformat(sep='T') 

    返回ISO8601格式的日期和时间,格式为:YYYY-MM-DDTHH:MM:SS.mmmmmm,或者当微秒为0时为YYYY-MM-DDTHH:MM:SS。如果utcoffset不返回None,则在时间后面添加符号的相对时间,格式为:YYYY-MM-DDTHH:MM:SS.mmmmmm+HH:MM ;当微秒为0时YYYY-MM-DDTHH:MM:SS+HH:MM。

    参数sep是分隔日期和时间之间字符,默认为T。

    例子:

    #python 3.4.3

    import datetime

     

    class TZ(datetime.tzinfo):

        def utcoffset(self, dt): return datetime.timedelta(minutes=-399)

     

    dt = datetime.datetime(2015, 12, 25, tzinfo=TZ()).isoformat(' ')

    print('dt:', dt)

    结果输出如下:

    dt: 2015-12-25 00:00:00-06:39

     

    datetime.__str__() 

    返回日期时间的格式化字符串,str(d)等同d.isoformat(‘ ‘)。

    例子:

    #python 3.4.3

    import datetime

     

    class TZ(datetime.tzinfo):

        def utcoffset(self, dt): return datetime.timedelta(minutes=-399)

    dt = datetime.datetime(2015, 12, 25, tzinfo=TZ())

    print('dt:', str(dt))

    结果输出如下:

    dt: 2015-12-25 00:00:00-06:39

     

    datetime.ctime() 

    返回像C语言格式化的日期时间表示。

    例子:

    #python 3.4.3

    import datetime

     

    class TZ(datetime.tzinfo):

        def utcoffset(self, dt): return datetime.timedelta(minutes=-399)

    dt = datetime.datetime(2015, 12, 25, tzinfo=TZ())

    print('dt:', dt.ctime())

    结果输出如下:

    dt: Fri Dec 25 00:00:00 2015

     

    datetime.strftime(format) 

    通过指定的格式字符串来格式时间。它与strtime()和strptime()函数的格式相同。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.today()

    print('dt:', dt.strftime("%A, %d. %B %Y %I:%M%p"))

    结果输出如下:

    dt: Monday, 16. November 2015 11:32AM

     

    datetime.__format__(format)

    返回格式与datetime.strftime()一样。

    例子:

    #python 3.4.3

    import datetime

     

    dt = datetime.datetime.today()

    print('dt:', dt.__format__("%A, %d. %B %Y %I:%M%p"))

    结果输出如下:

    dt: Monday, 16. November 2015 11:50AM

     


    蔡军生 QQ:9073204  深圳



沪ICP备19023445号-2号
友情链接