例1
>>> import datetime # 下面的例子就不重复这个导入操作了
>>>
datetime.date()
>>> dt = datetime.date(2019, 12, 12)
>>> dt
datetime.date(2019, 12, 12)
>>> dt.year
2019
>>> dt.month
12
>>> dt.day
12
>>>
datetime.time()
- 提供
hour
, minute
, second
, microsecond
, tzinfo
属性
>>> datetime.time.fromisoformat('04:23:01')
datetime.time(4, 23, 1)
>>> datetime.time.fromisoformat('04:23:01.000384')
datetime.time(4, 23, 1, 384)
>>> datetime.time.fromisoformat('04:23:01+04:00')
datetime.time(4, 23, 1, tzinfo=datetime.timezone(datetime.timedelta(seconds=14400)))
>>>
例2
>>> from datetime import datetime, timedelta # 下面的例子就不重复这个导入操作了
>>>
datetime.datetime()
>>> dt = datetime(2019, 12, 12)
>>> dt.today()
datetime.datetime(2019, 12, 12, 21, 54, 34, 746828)
>>> dt.now()
datetime.datetime(2019, 12, 12, 21, 54, 42, 291514)
>>>
datetime.timedelta()
>>> t1 = datetime.now()
>>> t2 = timedelta(hours=1)
>>> (t1 + t2).strftime("%Y-%m-%d %H:%M:%S")
'2019-12-12 22:56:12'
补充
写法一
import datetime
from datetime import datetime
写法二
from datetime import datetime
import datetime
建议的写法
import datetime as dt
from datetime import datetime