- datetime模塊
- 創(chuàng)建datetime對(duì)象蜒滩,以及其包含的屬性
#coding=utf-8
from datetime import datetime,date,time
dt = datetime(2011,10,29,20,40,21)
a = (dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second)
#type tuple
print a,type(a)
#Extract date and time object
print dt.date(),dt.time()```
- date對(duì)象偶洋,不包含時(shí)間,創(chuàng)建方法和datetime一樣
from datetime import date```
- timedelta對(duì)象土居,表示增量時(shí)間
from datetime import timedelta
#增量時(shí)間為2天,6小時(shí)
a = timedelta(days=2,hours=6)
b = timedelta(hours=4.5)
#c的增量時(shí)間是2天10個(gè)半小時(shí)
c = a + b
print(c)
print(a)
print(c.days)
print(c.seconds)
#c.seconds指未滿一天的seconds
print(c.seconds/3600)
print(c.total_seconds()/3600)```
- datetime對(duì)象的一些方法
- datetime.strptime()
from datetime import datetime
text = '2016-05-31'
y = datetime.strptime(text,'%Y-%m-%d')
z = datetime.now()
diff = z - y
print(diff)```
- datetime.strftime()
#使用strftime()函數(shù)將datetime對(duì)象轉(zhuǎn)換為字符串
nice_z = datetime.strftime(z,'%A %B %d, %Y')
print(nice_z)```
- datetime.replace()
對(duì)時(shí)間序列數(shù)據(jù)進(jìn)行聚合和分組的時(shí)候圆雁,替換datetime中的一些字段
print dt.replace(minute=0,second=0)
print dt
print((date.today()+timedelta(days=1)).replace(day=1))
但是并沒有改變?cè)械膁atetime對(duì)象dt```
- 一些例子
- (1)
#指定日期與時(shí)間,建立一個(gè)datetime實(shí)例
from datetime import datetime
a = datetime(2012,9,23)
print(a+timedelta(days=10))
b = datetime(2012,12,21)
d = b - a
print(d.days)
now = datetime.today()
print(now)
print(now+timedelta(minutes=10))
#datetime會(huì)自動(dòng)處理閏年
a = datetime(2012,3,1)
b = datetime(2012,2,28)
print(a-b)
print((a-b).days)```
- (2) 計(jì)算最后一個(gè)周五出現(xiàn)的日期
from datetime import datetime, timedelta
定義一個(gè)星期名字的數(shù)組
weekdays = ['Monday','Tuesday','Wednesday','Thursday','Friday',
'Saturday','Sunday']
def get_previous_byday(dayname,start_date=None):
if start_date is None:
start_date = datetime.today()
#獲取當(dāng)前日期的星期幾
day_num = start_date.weekday()
#獲取到目標(biāo)周幾的序號(hào)
day_num_target = weekdays.index(dayname)
#確定是過了多少天,如果恰好整除則說明是7天
day_ago = (7 + day_num - day_num_target) % 7
if day_ago == 0:
day_ago = 7
#使用datetime的加減計(jì)算出那一天
target_date = start_date - timedelta(days=day_ago)
return target_date
print(get_previous_byday("Monday"))
print(get_previous_byday("Wednesday"))
print(get_previous_byday("Sunday",datetime(2016,6,22)))```
- (3) 計(jì)算日期范圍
#當(dāng)前月份中循環(huán)每一天,找到一個(gè)計(jì)算這個(gè)日期范圍
from datetime import datetime,date,timedelta
#replace()方法將day替換成1,這樣就能快速找到每個(gè)月份的第一天\
#date對(duì)象和datetime對(duì)象的區(qū)別是date只包含日期
print((date.today()+timedelta(days=1)).replace(day=1))
import calendar
def get_month_range(start_date=None):
if start_date is None:
#獲取每一月的第一天
start_date = date.today().replace(day=1)
#序列解包,找出每月的日期范圍,返回的第一個(gè)參數(shù)是這個(gè)月第一天是星期幾
_, days_in_month = calendar.monthrange(start_date.year,start_date.month)
end_date = start_date + timedelta(days=days_in_month)
return(start_date,end_date)
#定義一個(gè)每一天的增量
a_day = timedelta(days=1)
#返回的都是datetime對(duì)象
first_day,last_day = get_month_range()
#注意last_day是下一個(gè)月的開始
print(last_day)
while first_day < last_day:
print(first_day)
first_day += a_day
#另外,也可以為日期迭代創(chuàng)建一個(gè)如range()函數(shù)一樣的
def date_range(start,stop,step):
while start < stop:
yield start
start += step
#使用這個(gè)date_range(),返回的是迭代器,使用date對(duì)象也許更加好
for date in date_range(datetime(2016,5,15),datetime(2016,6,22),timedelta(days=1)):
print(date)```
- (4) 自己創(chuàng)建解析函數(shù)將字符串轉(zhuǎn)化為datetime對(duì)象
strptime()的性能并不好,因此可以自己進(jìn)行處理
def parse_ymd(s):
year_s,mon_s,day_s = s.split('-')
#datetime創(chuàng)建實(shí)例需要int類型,而不是字符串型的
return datetime(int(year_s),int(mon_s),int(day_s))```