时间

2016-09-19  本文已影响9人  bigtom

datetime, timedelta

datetime为时间类,timedelta为时间差类

from datetime import datetime,timedelta
today = datetime.today()
week = timedelta(days=7)
lastWeek = today - week
print lastWeek

d = datetime(1949,10,1)
print (today-d).days

caldendar 找出当月的日期范围

from datetime import datetime,timedelta, date
import calendar

def get_month_range(start_date=None):
    if start_date is None:
        start_date = date.today().replace(day=1)
    _, 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)
print get_month_range()  #(datetime.date(2016, 9, 1), datetime.date(2016, 10, 1))

字符串转换为日期

from datetime import datetime
text = "2012-09-20"
y = datetime.strptime(text, '%Y-%m-%d')
print y

日期转换为字符串

from datetime import datetime
t = datetime(2012,9,23,21,37,4)
print datetime.strftime(t,'%A %B %d, %Y')
上一篇下一篇

猜你喜欢

热点阅读