python3: 数字日期和时间(2)
12.基本的日期与时间转换
Q: 你需要执行简单的时间转换,比如天到秒,小时到分钟等的转换
A: 为了执行不同时间单位的转换和计算,请使用 datetime
模块。 比如,为了表示一个时间段,可以创建一个 timedelta
实例,就像下面这样:
>>> from datetime import timedelta >>> a = timedelta(days=2, hours=6) >>> b = timedelta(hours=4.5) >>> c = a + b >>> c.days 2 >>> c.seconds 37800 >>> c.seconds / 3600 10.5 >>> c.total_seconds() / 3600 58.5 >>>
如果你想表示指定的日期和时间,先创建一个 datetime
实例然后使用标准的数学运算来操作它们。比如:
>>> from datetime import datetime >>> a = datetime(2012, 9, 23) >>> print(a + timedelta(days=10)) 2012-10-03 00:00:00 >>> >>> b = datetime(2012, 12, 21) >>> d = b - a >>> d.days 89 >>> now = datetime.today() >>> print(now) 2012-12-21 14:54:43.094063 >>> print(now + timedelta(minutes=10)) 2012-12-21 15:04:43.094063 >>> #datetime会自动处理闰年 >>> a = datetime(2012, 3, 1) >>> b = datetime(2012, 2, 28) >>> a - b datetime.timedelta(2) >>> (a - b).days 2 >>> c = datetime(2013, 3, 1) >>> d = datetime(2013, 2, 28) >>> (c - d).days 1 >>>
13. 计算最后一个周五的日期【第三方包python-dateutil
】
>>> from datetime import datetime >>> from dateutil.relativedelta import relativedelta >>> from dateutil.rrule import * >>> d = datetime.now() >>> print(d) 2012-12-23 16:31:52.718111 >>> # Next Friday >>> print(d + relativedelta(weekday=FR)) 2012-12-28 16:31:52.718111 >>> >>> # Last Friday >>> print(d + relativedelta(weekday=FR(-1))) 2012-12-21 16:31:52.718111 >>>
14. 计算当前月份的日期范围
15. 字符串转换为日期
from datetime import datetime def parse_ymd(s): year_s, mon_s, day_s = s.split('-') return datetime(int(year_s), int(mon_s), int(day_s))
16.结合时区的日期操作
日行一善, 日写一撰