python时间处理之date

# -*- coding: utf-8 -*-

from datetime import *

import time

# 1. date常用的类方法和类属性


#date对象所能表示的最大日期: 9999-12-31

print 'date.max',date.max

#date对象所能表示的最小日期: 0001-01-01

print 'date.min',date.min

#返回一个表示当前本地日期的date对象: 2012-09-12

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

#将Gregorian日历时间转换为date对象(Gregorian Calendar :一种日历表示方法,类似于我国的农历,西方国家使用比较多): 

#1347442385.972转换为2012-09-12

print 'date.fromtimestamp():', date.fromtimestamp(time.time()) 


# 2. date提供的实例方法和属性


#获得年 月 日

now = date(2012,9,17)

print 'now.year:',now.year

print 'now.month:',now.month

print 'now.day:',now.day

#date.replace(year, month, day):生成一个新的日期对象

#用参数指定的年,月,日代替原有对象中的属性。(原有对象仍保持不变)

tomorrow = now.replace(day = 18)

nextmonth = now.replace(month = 10)

nextyear = now.replace(year = 2013)

print "tomorrow:",tomorrow," nextyear:",nextyear," nextmonth:",nextmonth

# 返回日期对应的time.struct_time对象;

# print: time.struct_time(tm_year=2012, tm_mon=9, tm_mday=17, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=261, tm_isdst=-1)

print "date.timetuple(): ",now.timetuple() 

# 返回日期对应的Gregorian Calendar日期;

#print: 734763

print "date.toordinal(): ",str(now.toordinal())

#返回weekday,如果是星期一,返回0;如果是星期2,返回1,以此类推; 

#print:0

print "date.weekday(): ",now.weekday()

#返回weekday,如果是星期一,返回1;如果是星期2,返回2,以此类推;

#print: 1

print 'date.isoweekday(): ',now.isoweekday() 

#返回格式如(year,month,day)的元组;

#print: (2012, 38, 1)

print 'date.isocalendar():',now.isocalendar() 

#返回格式如'YYYY-MM-DD’的字符串;

#print: '2012-09-17'

print 'date.isoformat():',now.isoformat()

#date.strftime(fmt):自定义格式化字符串。在下面详细讲解。


#3. 日期操作 


#当前日期为2012年9月12日

now = date.today()

tomorrow = now.replace(day = 13)

delta = tomorrow - now

print "now: ",now,"tomorrow: ",tomorrow

#计算出间隔时间

#print: timedelta:  1 day, 0:00:00

print "timedelta: ",delta

#print: now + delta = tomorrow : 2012-09-13

print "now + delta = tomorrow :",now + delta

#print: tomorrow > now : True

print "tomorrow > now :",tomorrow > now

#print: tomorrow < now : False

print "tomorrow < now :",tomorrow < now


转载于:https://my.oschina.net/workhelu/blog/335885

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值