1. 日期转时间字符串不自动补零
对于Linux 需要在字段类型前加上 -
对于win 需要再字段类型前加上 #
- 代码示例
import time
timestamp = 1568171336
time_format = "%Y-%#m-%#d %H:%M:%S"
time_local = time.localtime(timestamp)
new_date = time.strftime(time_format, time_local)
print(new_date)
- 结果
2019-9-11 11:08:56
来自 Python datetime formatting without zero-padding
Accepted answer not a proper solution (IMHO) The proper documented methods:
In Linux "#" is replaced by "-":
%-d, %-H, %-I, %-j, %-m, %-M, %-S, %-U, %-w, %-W, %-y, %-Y
In Windows "-" is replaced by "#":
%#d, %#H, %#I, %#j, %#m, %#M, %#S, %#U, %#w, %#W, %#y, %#Y
- Linux
mydatetime.strftime('%-m/%d/%Y %-I:%M%p')
- Windows
mydatetime.strftime('%#m/%d/%Y %#I:%M%p')
本文介绍在Linux和Windows环境下,如何使用Python将日期转换为时间字符串,并去除前导零。通过在格式字符串中使用特定的占位符,可以实现在不同操作系统上的正确显示。

被折叠的 条评论
为什么被折叠?



