python 时间戳转日期 不自动补零 without zero-padding

1. 时间戳转日期

  • 代码
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-09-11 11:08:56

2. 不自动补零

对于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')
posted @ 2019-09-11 15:36  白应非  阅读(2186)  评论(0编辑  收藏  举报