
from datetime import datetime
import time
# 获取当前的时间
now = datetime.now()
# 获取年月日
print('年:', now.year)
print('月:', now.month)
print('日:', now.day)
# datetime转换成字符串
print(now.strftime("%Y-%m-%d %H:%M:%S"))
# 字符串转换成datetime
time_dt = datetime.strptime('2022-04-17 22:06:20', "%Y-%m-%d %H:%M:%S")
# 计算两个datetime的时间差
print((now-time_dt).seconds)
# 把字符串转成时间戳形式
print(time.mktime(time.strptime('2022-04-17 22:06:20', "%Y-%m-%d %H:%M:%S")))
#把时间戳转成字符串形式
sp = time.time()
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(sp)))
# 把datetime类型转外时间戳形式
print(time.mktime(time_dt.timetuple()))输出结果:
年: 2022 月: 4 日: 17 2022-04-17 22:10:25 245 1650204380.0 2022-04-17 22:10:25 1650204380.0