时间和日期
![](https://i-blog.csdnimg.cn/blog_migrate/77e0775d0cc21006e15b032c70653f3e.png)
(
图中错误修正:dt_obj.strftime(format))
import time, datetime
1. datetime obj
1) datetime
datetime.datetime.now()
datetime.datetime.now() - datetime.timedelta(days=42)
datetime.datetime.combine(datetime.date.today(), datetime.time.min)
datetime.datetime(*time.localtime()[0:6])
datetime.datetime.strptime("2016-05-04 00:00:00", "%Y-%m-%d %H:%M:%S")
datetime.datetime.fromtimestamp(1462291200.0)
datetime.datetime.fromtimestamp(time.mktime(time.gmtime())) == datetime.datetime.utcfromtimestamp(time.mktime(time.localtime()))
2) date
datetime.datetime.now().date()
datetime.date.today()
datetime.date.today() + datetime.timedelta(days=42)
3) timedelta
datetime.timedelta(days=42)
# datetime.timedelta(days=42).total_seconds()
(datetime.datetime.now() - datetime.datetime(2016,5,4,0,0,0))
# (datetime.datetime.now() - datetime.datetime(2016,5,4,0,0,0)).total_seconds()
2. time tuple
time.localtime()
time.gmtime()
datetime.datetime.now().timetuple()
time.strptime("2016-05-04 00:00:00", "%Y-%m-%d %H:%M:%S")
time.localtime(1462291200.0)
3. string
datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())
4. time stamp
time.time()
time.mktime(time.localtime())
time.mktime(time.gmtime())
int(time.time()) + 86400 * days
- 迭代:
import datetime
begin, end = ‘20151101’, datetime.datetime.today().strftime("%Y%m%d")
begin_tuple, end_tuple = datetime.datetime.strptime(begin, "%Y%m%d”), datetime.datetime.strptime(end, "%Y%m%d”)
mid_tuple = begin_tuple
while mid_tuple < end_tuple:
mid = mid_tuple.strftime("%Y%m%d")
print mid
mid_tuple += datetime.timedelta(days=30)
- dateutil库:
import datetime
from dateutil.rrule import rrule, MONTHLY
begin_day = datetime.datetime.strptime("2015-11-01", "%Y-%m-%d")
end_day = (datetime.datetime.today() + datetime.timedelta(days=31))
split_days = rrule(MONTHLY,dtstart=begin_day,until=end_day)
for ld, rd in zip(*[iter(split_days[i:]) for i in range(2)]):
print ld, rd
- 其他问题:
ISO Time (ISO 8601) in Python?
How to parse an ISO 8601-formatted date?
- 参考: