python程序能用很多方式处理日期和时间,转换日期格式是一个常见的功能。
1、time模块
- 1.1、获取当前时间戳(unix时间戳)
import time tick = time.time() print(tick)
- 1.2、# 获取时间元组
import time t = time.localtime() # 可传入unix时间戳进行转换 print(t)
- 1.3、获取格式化时间
import time# 时间戳转换 t = time.ctime() print(t)# 时间元组转换 time_tuple = time.localtime() t = time.asctime(time_tuple) print(t)
- 1.4、时间元组转格式化日期
import timet = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()) print(t) t = time.strftime("%y-%m-%d %H:%M:%S", time.localtime()) print(t)
- 1.5、格式化日期转时间元组
import time time_tuple = time.strptime("2024-04-02 16:31:30", "%Y-%m-%d %H:%M:%S") print(time_tuple)
- 1.6、时间元组转时间戳
t = time.mktime(time_tuple) print(t)
- 1.7、用于计算程序运行耗费时间
import time tick = time.perf_counter_ns() print(tick)
- 1.8、休眠n秒
import time print(1) time.sleep(2) print(2)
2、calendar模块
- 获取某月日历:
import calendar cal = calendar.month(2024, 5) print(cal)
3、datetime模块
- 3.1、获取当天日期
import datetime print(datetime.datetime.now()) print(datetime.datetime.today())
- 3.2、单独获取当前的年月日时分秒
import datetime t = datetime.datetime.now() print(t.year) print(t.month) print(t.day)
- 3.3、计算n天之后的日期
import datetime t = datetime.datetime.today() n = t + datetime.timedelta(days=7) print(n)
- 3.4、计算两个日期的时间差
import datetime t1 = datetime.datetime(2024, 4, 2, 17, 50, 2) print(t1) t2 = datetime.datetime(2024, 4, 8, 17, 50, 2) print(t2) delta = t2 - t1 print(delta.total_seconds())