ARTICLE DETAIL

建站实战干货

来自一线的建站与推广经验沉淀,每一条都经过真实交付验证。

Python 获取当前时间、格式化与简单计算

2026/9/17 1:48:48 拓冰建站 浏览量
Python 获取当前时间、格式化与简单计算

Python 获取当前时间、格式化与简单计算

使用datetime

import datetimeprint(datetime.date.today())  # 当前日期如 2024-01-29
print(datetime.datetime.now())  # 当前时间 2024-01-29 06:04:57.017250  
print(datetime.datetime.now().weekday())  # 一周中的第几天 0-6 周一为0
print(datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S'))  # 格式化输出# 字符串转日期
parse_date = datetime.datetime.strptime('2024-01-27', '%Y-%m-%d')
print(parse_date.year, parse_date.month, parse_date.day)  # 2024 1 27# 日期计算
parse_date = datetime.datetime.strptime('2024-01-27', '%Y-%m-%d')
after_date = parse_date + datetime.timedelta(days=1)  # 加一天 days=-1为减一天print((after_date - parse_date).days)  # 两个日期相差天数

使用time

import timeprint(time.time())  # 当前时间戳 1706480585.666243current_time = time.localtime()
print(current_time.tm_year)  # 年
print(current_time.tm_mon)  # 月
print(current_time.tm_mday)  # 日
print(current_time.tm_wday)  # 一周中的第几天 0-6 周一为0
print(current_time.tm_yday)  # 一年中的第几天 0-366
print(time.strftime('%Y-%m-%d %H:%M:%S',))  # 格式化输出