一.获取当前日期
>>> from datetime import datetime >>> now=datetime.now() >>> print now 2017-03-14 10:53:36.178612
二.日期格式化
1.datetime转换为str
>>> now2=now.strftime('%Y-%m-%d %H:%M:%S') >>> print now2 2017-03-14 10:53:36
2.str转换为datetime
>>> from datetime import datetime >>> cday = datetime.strptime('2015-6-1 18:19:59', '%Y-%m-%d %H:%M:%S') >>> print(cday) 2015-06-01 18:19:59
3.datetime转换为timestamp
>>> from datetime import datetime >>> dt = datetime(2015, 4, 19, 12, 20) # 用指定日期时间创建datetime >>> dt.timestamp() # 把datetime转换为timestamp 1429417200.0
4.timestamp转换为datetime
>>> from datetime import datetime >>> t = 1429417200.0 >>> print(datetime.fromtimestamp(t)) 2015-04-19 12:20:00
三.日期加减
>>> from datetime import datetime, timedelta >>> now = datetime.now() >>> now datetime.datetime(2015, 5, 18, 16, 57, 3, 540997) >>> now + timedelta(hours=10) datetime.datetime(2015, 5, 19, 2, 57, 3, 540997) >>> now - timedelta(days=1) datetime.datetime(2015, 5, 17, 16, 57, 3, 540997) >>> now + timedelta(days=2, hours=12) datetime.datetime(2015, 5, 21, 4, 57, 3, 540997)
本文转自廖雪峰老师的python教程