In [1]:
from calendar import TextCalendar, HTMLCalendar
tc = TextCalendar(firstweekday=6)
tc.prmonth(2016, 3)
datetime
模块解决了绝大部分时间与日期相关的操作问题,其中包含了:
timedelta
与时间计算相关的类;time
时间相关的类;date
日期相关的类;datetime
时间和日期;tzinfo
/timezone
与时区相关的类(timezone
是 Python 3.2 之后新加入的);它们的继承关系如下:
In [2]:
"""
object
timedelta
tzinfo
timezone
time
date
datetime
"""
pass
In [3]:
import time as _time
from datetime import date, time, datetime
In [4]:
d1 = date(2016, 3, 29)
d2 = date.today()
d3 = date.fromtimestamp(_time.time())
print(d1)
print(d2)
print(d3)
获得 date
对象之后,可以分别获取年、月、日等属性(strftime
也是通用的格式化方法,将在后面介绍):
In [5]:
print("{}/{}/{}".format(d2.day, d2.month, d2.year))
# date.timetuple() 返回 time 模块中的 struct_time 结构,可以直接转换成 Tuple
print("time.struct_time: {}".format(tuple(d2.timetuple())))
# 星期数
print("Monday is 0: {}\nMonday is 1: {}".format(d2.weekday(), d2.isoweekday()))
In [6]:
t1 = time(22, 57, 6, 6)
t2 = datetime.now().time()
print(t1)
print(t2)
In [7]:
dt1 = datetime(2016, 3, 30, 22, 2)
dt2 = datetime.now()
dt3 = datetime.fromtimestamp(_time.time())
print(dt1)
print(dt2)
print(dt3)
从 datetime.datetime
中我们可以获取 date
和 time
,同样也可以通过 date
和 time
组合得来:
In [8]:
dt = datetime.now()
dt = datetime.fromtimestamp(_time.time())
d = dt.date()
t = dt.time()
print("Date: {}\nTime: {}".format(d, t))
print("Datetime: {}".format(datetime.combine(date.today(), time(2,3,3))))
In [9]:
from datetime import timedelta
td = timedelta(weeks=1, days=2, hours=3,minutes=4, seconds=0, microseconds=0, milliseconds=0)
print("Time duration: {}".format(td))
既然是时间段,那就可以通过两个时间点相减得到:
In [10]:
current = datetime.now()
today = datetime.combine(date.today(), time(0,0,0))
td = current - today
print("{:.0f}s of Today".format(td.total_seconds()))
today = date.today()
lastyear = today.replace(year=today.year-1)
print(today - lastyear)
t1 = current.time()
t2 = time(0, 0, 0)
try:
print(t1 - t2)
except TypeError as err:
print(err)
In [11]:
print(datetime.strftime.__doc__)
print(datetime.strptime.__doc__)
In [12]:
fmat = "%y-%m-%d"
dt = datetime.now()
s = dt.strftime(fmat)
print(s)
print(datetime.strptime(s, fmat))
可以通过 strftime() and strptime() Behavior 查看转换格式表,Python 使用的格式与 C standard(1989)
是一致的,不过需要注意的是,所有格式都是 zero-padded
,也就是自动补零的,如果想要去掉补零,可以用 %-m
等方式,但据说在 Windows 系统上是不能用的:D
In [13]:
fmat = "%y/%-m/%-d"
dt = datetime.now()
dt = dt - timedelta(days=22)
print(dt.strftime(fmat))
# 当然也可以用
print("{}/{}/{}".format(dt.strftime("%y"), dt.month, dt.day))