# 1. datetime:日期和时间值管理

datetime包含一些函数和类，用于完成日期和时间的解析、格式化和算术运算。

## 1.1 时间

import datetime

t = datetime.time(1, 2, 3)
print(t)
print("hour       :", t.hour)
print("minute     :", t.minute)
print("second     :", t.second)
print("microsecond:", t.microsecond)
print("tzinfo     :", t.tzinfo)

time实例只包含时间值，而不包含与时间相关的日期值。

import datetime

print("Earliest  :", datetime.time.min)
print("Latest    :", datetime.time.max)
print("Resolution:", datetime.time.resolution)

min和max类属性可以反映一天中的合法时间范围。

time的分辨率被限制为整微秒值。

import datetime

for m in [1, 0, 0.1, 0.6]:
try:
print("{:02.1f} :".format(m),
datetime.time(0, 0, 0, microsecond=m))
except TypeError as err:
print("ERROR:", err)

## 1.2 日期

import datetime

today = datetime.date.today()
print(today)
print("ctime  :", today.ctime())
tt = today.timetuple()
print("tuple  : tm_year  =", tt.tm_year)
print("         tm_mon   =", tt.tm_mon)
print("         tm_mday  =", tt.tm_mday)
print("         tm_hour  =", tt.tm_hour)
print("         tm_min   =", tt.tm_min)
print("         tm_sec   =", tt.tm_sec)
print("         tm_wday  =", tt.tm_wday)
print("         tm_yday  =", tt.tm_yday)
print("         tm_isdst =", tt.tm_isdst)
print("ordinal:", today.toordinal())
print("Year   :", today.year)
print("Mon    :", today.month)
print("Day    :", today.day)

import datetime
import time

o = 733114
print("o               :", o)
print("fromordinal(o)  :", datetime.date.fromordinal(o))

t = time.time()
print("t               :", t)
print("fromtimestamp(t):", datetime.date.fromtimestamp(t))

import datetime

print("Earliest  :", datetime.date.min)
print("Latest    :", datetime.date.max)
print("Resolution:", datetime.date.resolution)

import datetime

d1 = datetime.date(2008, 3, 29)
print("d1:", d1.ctime())

d2 = d1.replace(year=2009)
print("d2:", d2.ctime())

## 1.3 timedelta

import datetime

print("microseconds:", datetime.timedelta(microseconds=1))
print("milliseconds:", datetime.timedelta(milliseconds=1))
print("seconds     :", datetime.timedelta(seconds=1))
print("minutes     :", datetime.timedelta(minutes=1))
print("hours       :", datetime.timedelta(hours=1))
print("days        :", datetime.timedelta(days=1))
print("weeks       :", datetime.timedelta(weeks=1))

import datetime

for delta in [datetime.timedelta(microseconds=1),
datetime.timedelta(milliseconds=1),
datetime.timedelta(seconds=1),
datetime.timedelta(minutes=1),
datetime.timedelta(hours=1),
datetime.timedelta(days=1),
datetime.timedelta(weeks=1),
]:
print("{:15} = {:8} seconds".format(
str(delta), delta.total_seconds())
)

## 1.4 日期算术运算

import datetime

today = datetime.date.today()
print("Today    :", today)

one_day = datetime.timedelta(days=1)
print("One day  :", one_day)

yesterday = today - one_day
print("Yesterday:", yesterday)

tomorrow = today + one_day
print("Tomorrow :", tomorrow)

print()
print("tomorrow - yesterday:", tomorrow - yesterday)
print("yesterday - tomorrow:", yesterday - tomorrow)

timedelta对象还支持与整数、浮点数和其他timedelta实例的算术运算。

import datetime

one_day = datetime.timedelta(days=1)
print("1 day    :", one_day)
print("5 days   :", one_day * 5)
print("1.5 days :", one_day * 1.5)
print("1/4 day  :", one_day / 4)

# assume an hour for lunch
work_day = datetime.timedelta(hours=7)
meeting_length = datetime.timedelta(hours=1)
print("meetings per day :", work_day / meeting_length)

## 1.5 比较值

import datetime
import time

print("Times:")
t1 = datetime.time(12, 55, 0)
print("  t1:", t1)
t2 = datetime.time(13, 5, 0)
print("  t2:", t2)
print("  t1 < t2:", t1 < t2)

print()
print("Dates:")
d1 = datetime.date.today()
print("  d1:", d1)
d2 = datetime.date.today() + datetime.timedelta(days=1)
print("  d2:", d2)
print("  d1 > d2:", d1 > d2)

## 1.6 结合日期和时间

import datetime

print("Now    :", datetime.datetime.now())
print("Today  :", datetime.datetime.today())
print("UTC Now:", datetime.datetime.utcnow())
print()

FIELDS = [
"year", "month", "day",
"hour", "minute", "second",
"microsecond",
]

d = datetime.datetime.now()
for attr in FIELDS:
print("{:15}: {}".format(attr, getattr(d, attr)))

import datetime

t = datetime.time(1, 2, 3)
print("t :", t)

d = datetime.date.today()
print("d :", d)

dt = datetime.datetime.combine(d, t)
print("dt:", dt)

## 1.7 格式化和解析

datetime对象的默认字符串表示使用ISO-8601格式(YYYY-MM-DDTHH:MM:SS.mmmmmm)。可以使用strftime()生成其他格式。

import datetime

format = "%a %b %d %H:%M:%S %Y"

today = datetime.datetime.today()
print("ISO     :", today)

s = today.strftime(format)
print("strftime:", s)

d = datetime.datetime.strptime(s, format)
print("strptime:", d.strftime(format))

import datetime

today = datetime.datetime.today()
print("ISO     :", today)
print("format(): {:%a %b %d %H:%M:%S %Y}".format(today))

strptime/strftime格式化代码：

%a 星期几的缩写 "Wed"
%A 工作日全名 "Wednesday"
%w 工作日编号– 0（星期日）至6（星期六） "3"
%d 每月的某天（零填充） "13"
%b 缩写的月份名称 "Jan"
%B 月份全称 "January"
%m 一年中的月份 "01"
%y 没有世纪的年份 "16"
%Y 百年纪念 "2016"
%H 从24小时制开始的小时数 "17"
%I 从12小时制开始的小时数 "05"
%p 上午下午 "PM"
%M 分钟 "00"
%S "00"
%f 微秒 "000000"
%z 时区感知对象的UTC偏移量 "-0500"
%Z 时区名称 "EST"
%j 一年中的一天 "013"
%W 一年中的第几周 "02"
%c 当前语言环境的日期和时间表示 "Wed Jan 13 17:00:00 2016"
%x 当前语言环境的日期表示 "01/13/16"
%X 当前语言环境的时间表示 "17:00:00"
%% 文字%字符 "%"

## 1.8 时区

datetime在类timezone中确实包含一个原生实现，该类使用了一个固定的UTC偏移。这个实现不支持一年中不同日期有不同的偏移值，如有些地方采用夏令时，或者有些地方UTC偏移会随时间改变。

import datetime

min6 = datetime.timezone(datetime.timedelta(hours=-6))
plus6 = datetime.timezone(datetime.timedelta(hours=6))
d = datetime.datetime.now(min6)

print(min6, ":", d)
print(datetime.timezone.utc, ":",
d.astimezone(datetime.timezone.utc))
print(plus6, ":", d.astimezone(plus6))

# convert to the current system timezone
d_system = d.astimezone()
print(d_system.tzinfo, "      :", d_system)