datetime–基本的日期和时间类型

常见操作

时间戳转iso

>>> times = 1605087051
>>> datetime.date.fromtimestamp(times).isoformat()
'2020-11-11'

iso转时间戳

>>> times = '2020-11-11'
>>> datetime.datetime.strptime(times, '%Y-%m-%d').timestamp()
1602259200.0

 

timedelta

表示两个 date 对象或者 time 对象,或者 datetime 对象之间的时间间隔,精确到微秒。

可用于两个datetime对象的相加减运算

>>> d1 = datetime.timedelta(days=10)
>>> d1
datetime.timedelta(10)
>>> datetime.datetime(2020, 1, 1) + d1
datetime.datetime(2020, 1, 11, 0, 0)

 

date

初始化

>>> from datetime import date
>>> date(1994, 12, 31)
datetime.date(1994, 12, 31)
>>> date.fromisoformat('2019-12-04')
datetime.date(2019, 12, 4)
>>> import time
>>> date.fromtimestamp(time.time())
datetime.date(2020, 11, 11)

datetime

datetimedate用法相近

>>> datetime.datetime.fromtimestamp(time.time())
datetime.datetime(2020, 11, 12, 14, 33, 5, 33660)
>>> str(datetime.datetime.fromtimestamp(time.time()))
'2020-11-12 14:35:15.213926'