Python3入门(十三)——常用内置模块之时间日期模块datatime
作者:互联网
1.日期时间模块——datatime
//其他模块例如time、calender等模块暂不展开
(1)获取当前时间:datatime.now():
from datetime import datetime now = datetime.now() print(now)
结果:
2019-06-09 20:58:13.533006
//如果仅仅使用import,则需要加全限定名:
import datetime print datetime.datetime.now()
(2) 构造指定时间:class datetime.datetime(year, month, day, hour=0, minute=0, second=0, microsecond=0, tzinfo=None)
from datetime import datetime dt = datetime(2019, 6, 9, 21, 2) print(dt)
结果:
2019-06-09 21:02:00
(3) 转换为timestamp
from datetime import datetime d = datetime(2019, 6, 9, 21, 2) dt = d.timestamp() print(dt)
结果:
1560085320.0 ——某些编程语言(如Java和JavaScript)的timestamp使用整数表示毫秒数,这种情况下只需要把timestamp除以1000就得到Python的浮点表示方法。使用fromtimestamp进行逆转换
(4)时间日期格式化
str转datetime:
from datetime import datetime dt = datetime.strptime('2015-6-1', '%Y-%m-%d') print(dt)
结果:
2015-06-01 00:00:00
datetime转str:
from datetime import datetime now = datetime.now() print(now.strftime('%Y%m%d'))
结果:
20190609
可以转为各种格式(例如%a, %M),全部格式参考官方文档:https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior
(5)时间偏移
引入timedetal类即可:可以直接通过 + -号运算
from datetime import datetime, timedelta now = datetime.now() now1 = now + timedelta(days=1) print(now1)
博文参考:https://blog.csdn.net/gty931008/article/details/80254806
标签:datatime,datetime,2019,模块,print,import,dt,now,Python3 来源: https://www.cnblogs.com/jiangbei/p/10994955.html