本文目录导读:

我来介绍几种在Python中生成自定义时间戳的方法:
使用 datetime 模块(最常用)
基本时间戳生成
from datetime import datetime
# 当前时间
now = datetime.now()
print(now) # 2024-01-15 10:30:45.123456
# 自定义格式的时间戳
timestamp = now.strftime("%Y%m%d_%H%M%S")
print(timestamp) # 20240115_103045
# 带毫秒的时间戳
timestamp_ms = now.strftime("%Y%m%d_%H%M%S_%f")[:-3]
print(timestamp_ms) # 20240115_103045_123
常用时间格式
from datetime import datetime
now = datetime.now()
# 不同格式示例
formats = {
"日期": "%Y-%m-%d",
"时间": "%H:%M:%S",
"日期时间": "%Y-%m-%d %H:%M:%S",
"紧凑型": "%Y%m%d_%H%M%S",
"中文格式": "%Y年%m月%d日 %H时%M分%S秒",
"ISO格式": "%Y-%m-%dT%H:%M:%S",
"文件名友好": "%Y-%m-%d_%H-%M-%S"
}
for name, fmt in formats.items():
print(f"{name}: {now.strftime(fmt)}")
生成特定时间的时间戳
from datetime import datetime, timedelta
# 指定时间
specific_time = datetime(2024, 1, 1, 0, 0, 0)
print(specific_time.strftime("%Y%m%d_%H%M%S")) # 20240101_000000
# 相对时间
now = datetime.now()
yesterday = now - timedelta(days=1)
next_week = now + timedelta(weeks=1)
print(f"昨天: {yesterday.strftime('%Y%m%d')}")
print(f"下周: {next_week.strftime('%Y%m%d')}")
使用 time 模块
import time
# 当前时间戳(秒)
current_timestamp = time.time()
print(f"Unix时间戳: {current_timestamp}")
# 格式化为自定义时间
local_time = time.localtime(current_timestamp)
formatted_time = time.strftime("%Y-%m-%d %H:%M:%S", local_time)
print(f"格式化时间: {formatted_time}")
生成随机时间戳
import random
from datetime import datetime, timedelta
def random_timestamp(start_date="2020-01-01", end_date="2024-12-31"):
"""生成指定日期范围内的随机时间戳"""
start = datetime.strptime(start_date, "%Y-%m-%d")
end = datetime.strptime(end_date, "%Y-%m-%d")
# 计算时间差并生成随机时间
delta = end - start
random_days = random.randint(0, delta.days)
random_seconds = random.randint(0, 86400) # 一天内的随机秒数
random_date = start + timedelta(days=random_days, seconds=random_seconds)
return random_date
# 生成10个随机时间戳
for i in range(10):
ts = random_timestamp()
print(ts.strftime("%Y%m%d_%H%M%S"))
完整实用函数
from datetime import datetime
from typing import Optional
def generate_timestamp(
format_type: str = "compact",
use_milliseconds: bool = False,
custom_format: Optional[str] = None
) -> str:
"""
生成自定义时间戳
参数:
format_type: 格式类型 (compact, standard, iso, filename, chinese)
use_milliseconds: 是否包含毫秒
custom_format: 自定义格式(覆盖format_type)
返回:
格式化后的时间戳字符串
"""
now = datetime.now()
# 自定义格式优先
if custom_format:
return now.strftime(custom_format)
# 预定义格式
formats = {
"compact": "%Y%m%d_%H%M%S",
"standard": "%Y-%m-%d %H:%M:%S",
"iso": "%Y-%m-%dT%H:%M:%S",
"filename": "%Y-%m-%d_%H-%M-%S",
"chinese": "%Y年%m月%d日 %H时%M分%S秒",
"date_only": "%Y-%m-%d",
"time_only": "%H:%M:%S"
}
fmt = formats.get(format_type, formats["compact"])
# 添加毫秒
if use_milliseconds:
fmt = fmt.replace("%S", "%S_%f")[:-3] # 保留毫秒前3位
return now.strftime(fmt)
# 使用示例
if __name__ == "__main__":
print("紧凑型:", generate_timestamp("compact"))
print("标准型:", generate_timestamp("standard"))
print("ISO格式:", generate_timestamp("iso"))
print("文件名格式:", generate_timestamp("filename"))
print("中文格式:", generate_timestamp("chinese"))
print("带毫秒:", generate_timestamp("compact", use_milliseconds=True))
print("自定义:", generate_timestamp(custom_format="%Y年%m月%d日"))
在文件命名中的应用
import os
from datetime import datetime
def create_timestamped_file(content: str, prefix: str = "log"):
"""创建带时间戳的文件"""
timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"{prefix}_{timestamp}.txt"
with open(filename, "w", encoding="utf-8") as f:
f.write(f"创建时间: {datetime.now()}\n")
f.write(content)
print(f"文件已创建: {filename}")
return filename
# 使用
create_timestamped_file("测试内容", "backup")
常用格式化符号
| 符号 | 说明 | 示例 |
|---|---|---|
| %Y | 四位年份 | 2024 |
| %m | 两位月份 | 01-12 |
| %d | 两位日期 | 01-31 |
| %H | 24小时制 | 00-23 |
| %M | 分钟 | 00-59 |
| %S | 秒 | 00-59 |
| %f | 微秒 | 000000-999999 |
| %A | 星期全名 | Monday |
| %a | 星期缩写 | Mon |
| %B | 月份全名 | January |
| %b | 月份缩写 | Jan |
选择适合你需求的格式即可!