datetime 模块详解

1.import datetime

常用方法:

ttimedelta() 括号里默认为days,进行别的单位运算可以加上如hours = 1这样。除了进行减法运算,还可以进行加法运算。

>>> a = datetime.datetime.now() - datetime.timedelta(3)
>>> a
datetime.datetime(2018, 4, 8, 18, 11, 17, 128037)
>>> a = datetime.datetime.now() - datetime.timedelta(days = 5)
>>> a
datetime.datetime(2018, 4, 6, 18, 11, 37, 759721)
>>> a = datetime.datetime.now() - datetime.timedelta(hours = 3)
>>> a
datetime.datetime(2018, 4, 11, 15, 11, 51, 8094)

2.replace()

在括号里写入需要替换的年月日,即可替换。

>>> import datetime
>>> a = datetime.datetime.now()
>>> a
datetime.datetime(2018, 4, 11, 18, 23, 19, 153333)
>>> a.replace(year = 2016)
datetime.datetime(2016, 4, 11, 18, 23, 19, 153333)
>>> a.replace(month = 9)
datetime.datetime(2018, 9, 11, 18, 23, 19, 153333)

 

  

posted @ 2018-04-11 18:27  Roc_Atlantis  阅读(182)  评论(0编辑  收藏  举报