date 日期对象
date() 创建日期对象
d = datetime.date(2021, 5, 28)
d.year
d.month
d.day
d.min
d.max
d.resolution
today() 当前日期对象
now = datatime.date.today()
weekday() / isoweekday() 星期
d = date.fromisoformat('2021-05-28')
print(
d.weekday(),
d.isoweekday()
)
formtimstamp() 返回时间戳的本地时间格式
import time
import datetime
datetime.date.formtimestamp(time.time())
fromisoformat() 字符转date对象, 格式 YYYY-MM-DD
d = date.fromisoformat('2021-05-28')
print(d)
print(type(d))
isoformat() date对象转字符
d = date.fromisoformat('2021-05-28')
d_str = d.isoformat()
type(d_str)
日期运算
from datetime import date, timedelta
from datetime import date, timedelta
d = date.fromisoformat('2020-05-28')
one_day = timedelta(days=1)
before_day = d - one_day
after_day = d + one_day
print(
before_day,
type(before_day),
)
print(
after_day,
type(after_day),
)
print(
before_day - after_day,
after_day - before_day
)
print(
after_day > before_day,
after_day == before_day,
after_day < before_day,
)
time 时间
time() 创建时间对象
t = time(
hour=10,
minute=20,
second=24,
microsecond=1000
)
print(t)
fromiosformat() 字符转time对象
t = time.fromisoformat('10:20:24.001000')
print(t, type(t))
iosformat() 返回指定格式时间字符
t = time(
hour=10,
minute=20,
second=24,
microsecond=1000
)
print(
t.isoformat(timespec='hours')
)
datetime 日期时间
datetime() 创建对象
d = datetime(
year=2021,
month=5,
day=28,
hour=14,
minute=31,
second=10,
microsecond=1000
)
today() / now() 当前时间对象
print(
datetime.today(),
datetime.now()
)
fromtimestamp() 时间戳转datetime对象
d = datetime.fromtimestamp(time.time())
print(
d,
type(d)
)
timestamp() datetime对象转时间戳
d = datetime.fromtimestamp(time.time())
timestamp = d.timestamp()
print(
timestamp,
type(timestamp)
)
strptime() 字符转datetime对象
d = datetime.strptime(
'2021-05-28 14:31:10',
'%Y-%m-%d %H:%M:%S'
)
print(type(d))
strftime() datetime格式化输出
d = datetime.strptime(
'2021-05-28 14:31:10',
'%Y-%m-%d %H:%M:%S'
)
print(
d.strftime('%Y/%m/%d %H.%M.%S')
)
timedelta 时间差
t = timedelta(
days=1,
seconds=10,
microseconds=100,
milliseconds=1000,
minutes=1,
weeks=1
)
print(t)